#!/bin/bash -e

# Author: Andreas Tille <tille@debian.org>
#         with contributions from
#         Steffen Moeller <moeller@debian.org>
# 
# This script is just recording what I'm doing when realising new
# upstream versions of R packages.  It contains several steps all
# with the intention to
#
#  * reduce lintian warnings
#  * keep all packages in a "modern" packaging shape
#
# I tried to avoid calls to some local scripts I'm using to make
# this script available to other interested maintainers.

# Default to git username if DEBFULLNAME is not set.
FULLNAME=${DEBFULLNAME:-$(git config user.name)}
# Then default to /etc/password if user.name was not set.
FULLNAME=${FULLNAME:-$(getent passwd $(whoami) | cut -f5 -d: | cut -f1 -d,)}

STANDARDSVERSION=$(LC_ALL=C apt-cache policy debian-policy | grep Candidate | sed 's/^ *Candidate: \([0-9]\.[0-9]\.[0-9]\).*/\1/')
if [ "$STANDARDSVERSION" = "" ] ; then
  echo "E: Failure detecting latest Standards-Version"
  exit 1
fi
dhrneededversion="20180507"

SALSACIYAMLTEAMS="debian-med-packaging@lists.alioth.debian.org r-pkg-team@alioth-lists.debian.net"

if [ -n "$QUILT_PATCHES" ]; then
  if [ "debian/patches" != "$QUILT_PATCHES" ]; then
    echo "E: QUILT_PATCHES ($QUILT_PATCHES) found != 'debian/patches'. Unset QUILT_PATCHES and try again."
    exit 1
  fi
fi
export QUILT_PATCHES="debian/patches"

# maximum number of different lines after cme was run
# this helps raising a signal for d/control files of maintainers
# who possibly do not like cme formatting
MAXCMEDIFF=7

dch_git_commit () {
    dch "$1 (routine-update)" | sed -e 's/^/   /'
    git commit -a -m"routine-update: $1" | sed -e 's/^/   /'
}

function show_help()
{
  n=$(basename "$0")
  cat <<EOHELP
Usage: $n (-h|--help)   shows this info
       $n --clone URL   fetches and updates a remote repository
       $n               updates a Debian source tree

Other options:
     -b|--branch BRANCH: Git branch that should be updated, overrides 'debian-branch' in debian/gbp.conf
     -d|--debug:         output debugging information, very verbose
     -e|--experimental:  target distribution experimental instead of unstable
     -f|--force:         also runs on projects that are up to date
     -t|--no-tag:        do not tag version ready for upload
     -u|--no-uscan:      do not run uscan and thus ignore new upstream
     --no-build:         prevents building the package post routine-update operations

Run $n from the root of a local instance of a Debian package's repository.
Alternatively, give the ssh or https URL to clone the repository, first.

EOHELP
  unset n
  exit 0
}

FORCE=0
DEBUG=0
BUILDPACKAGE=1
NOTAG=0
NOUSCAN=0
TARGETDIST=unstable

for i in "$@"
do
case $i in
    -b|--branch)
    BRANCH=$2
    if echo "$BRANCH" | grep -q '^-' ; then
      echo "You need to specify a branch."
      exit 1
    fi
    if ! git rev-parse --quiet --verify "$BRANCH" >/dev/null ; then
      echo "Branch $BRANCH does not exist in this repository"
      exit 1
    fi
    shift
    shift
    ;;
    -d|--debug)
    DEBUG=1
    set -x
    shift
    ;;
    -e|--experimental)
    TARGETDIST=experimental
    shift
    ;;
    -f|--force)
    FORCE=1
    shift
    ;;
    -h|--help)
    show_help
    ;;
    --no-build)
    BUILDPACKAGE=0
    shift
    ;;
    -t|--no-tag)
    NOTAG=1
    shift
    ;;
    -u|--no-uscan)
    NOUSCAN=1
    shift
    ;;
esac
done

toolMissing=0
for tool in /usr/bin/git /usr/bin/gbp /usr/bin/dpkg /usr/bin/awk /usr/bin/dpkg-parsechangelog /usr/bin/lintian-brush
do
  if [ ! -x $tool ]; then
    echo "E: Please install missing tool '$tool'."
    toolMissing=$((toolMissing+1))
  fi
done
if [ $toolMissing -gt 0 ]; then
  echo "E: Missing essential tool."
  exit 1
fi
unset toolMissing

if [ ! -r "/usr/share/perl5/Dpkg/Substvars.pm" ]; then
  echo "E: Please install libdpkg-perl"
  exit 1
fi

if [ ! -r "/usr/share/perl5/Config/Model/Dpkg/Control/Source/StandardVersion.pm" ]; then
  echo "E: Please install libconfig-model-dpkg-perl"
  exit 1
fi

changingDirectoryTo=""
if [ "$1" = "clone" ] || [ "$1" = "--clone" ] ; then
  if [ -z "$2" ]; then
    echo "E: specify an URL for git to clone"
    exit 1
  fi
  echo "I: Cloning repository from '$2'"
  if ! gbp clone --pristine-tar "$2"; then
    echo "E: Could not clone repository '$2' - exiting."
    exit 1
  fi
  changingDirectoryTo=$(basename "$2" .git)
  if [ ! -d "$changingDirectoryTo" ]; then
    echo "E: Internal error - git should have created directory '$changingDirectoryTo'"
    exit 1
  fi
  #echo "D: Changing into directory '$changingDirectoryTo'"
  cd "$changingDirectoryTo"
fi

if [ ! -d debian ]; then
  echo "E: This tool needs to be run from a Debian package's root directory. But there is no debian folder."
  if echo "$1" | grep -E -q "^(http:|https:|ssh:|git:|git.ssh:)"; then
    echo "   It seems like the --clone instruction is missing. Try --help."
  fi
  exit 1
elif [ ! -r debian/changelog ]; then
  echo "E: This tool needs to be run from a Debian package's root directory. But there is no debian/changelog file."
  exit 1
elif [ ! -d .git ]; then
  echo "E: This tool is meant to update also the remote git repository with Debian's changes, but this is not a git repository."
  exit 1
fi

# This should *NOT* be default!  The script is for users who are doing *proper*
# builds in a chroot environment and do not want to bloat their local systems
# with unneeded Build-Depends.  Steffen, if you really want this please find
# some command line option to trigger it
#if ! dpkg-checkbuilddeps; then
#  echo "E: This machine misses above packages as build dependencies. If the package is already in Debian then run"
#  echo "      sudo apt-get build-dep"
#  echo "   to install what is missing and invoke $(basename $0) again, perferably from within $(pwd) with no arguments to spare redundant downloads."
#  exit 1
#fi

if ! LC_ALL=C git status | grep -q "working tree clean"; then
  echo "W: Repository is not clean. Running 'debian/rules clean' to remove leftover build files."
  fakeroot ./debian/rules clean | sed -e 's/^/   /'

  if ! LC_ALL=C git status | grep -q "working tree clean"; then
    echo "W: Repository is still not clean."

    if [ -d debian/patches ]; then
      if [ -d .pc ]; then
        echo "I: Running 'quilt pop -a' to unapply past patches"
        quilt pop -a | sed -e 's/^/   /'
        rm -rf .pc
      fi
    fi

    if ! LC_ALL=C git status | grep -q "working tree clean"; then
      echo "E: Ran out of ideas. Please run 'git status' and check."
      exit 1
    fi
  fi

fi

DIST=$(dpkg-parsechangelog | awk '/^Distribution:/ {print $2}')

cmedneededversion="2.107+nmu1"
cmedpkgversion=$(apt-cache policy libconfig-model-dpkg-perl | grep '^ \*\*\*' | sed 's/^ \*\+ *\([^ ]\+\) [0-9]\+/\1/')
if dpkg --compare-versions "$cmedpkgversion" lt $cmedneededversion ; then
  echo "E: System need at least libconfig-model-dpkg-perl version $cmedneededversion but has only version $cmedpkgversion"
  exit 1
fi
unset cmedpkgversion
unset cmedneededversion

DEBIANCONTROL="debian/control"
if [ -e debian/control.in ] ; then
  DEBIANCONTROL="debian/control debian/control.in"
fi

do_cme () {
cme fix dpkg-control
if [ "$(git diff)" != "" ] ; then
    if [ "$(git diff | grep -c '^-')" -gt $MAXCMEDIFF ] ; then
    echo 'W: ********** The command "cme fix dpkg-control" created a large diff **********'
    git diff
    read -rp "Do you want to continue this automatic process? [Yn]" res
    case $res in
          ''|[YyJj]* )
		    echo "I: Continue $(dirname "$0")"
                    ;;
          *)
                    echo "W: Please inspect the diff manually"
                    exit 1
                    ;;
    esac
  fi
  if  git diff | grep -q "^+Vcs-.*https://salsa.debian.org" ; then
    dch_git_commit "Reorder sequence of d/control fields by cme"
  fi
else
  # HACK: if dh-update-R might have messed up cme formatting force cme to restore it
  #       may be that hack can simply be droped due to bce1fa1f9379e2d7a1d38152d8b89fd3ca516a5d  FIXME
  if [ "$DHUPDATER" -eq 1 ] ; then
    # just calling `cme fix -save` does not change anything - so we force a decrease of
    # Standards-Version to let cme do "anything".  This needs to be discussed with cme authors
    sed -i 's/^[Ss]tandards-[Vv]ersion: .*/Standards-Version: 4.0.0/' debian/control
    cme fix -save dpkg-control
  fi
fi
}

# No need to git pull if repo was just cloned
if [ -z "$changingDirectoryTo" ]; then
  echo "I: Retrieved latest version via 'git pull'"
  if [ -v BRANCH ]; then
    gbp pull --debian-branch="$BRANCH" | sed -e 's/^/   /'
  else
    gbp pull | sed -e 's/^/   /'
  fi
fi

if [ -e debian/gbp.conf ] ; then
  if grep -q "^debian-branch" debian/gbp.conf ; then
    GBRANCH=$(grep "^debian-branch" debian/gbp.conf | tail -n1 | sed 's/^debian-branch[[:space:]]*=[[:space:]]*//')
    if [ -v BRANCH ]; then
      echo "I: Debian branch is: $BRANCH, set by --branch. Ignoring $GBRANCH set in debian/gbp.conf."
    else
      BRANCH=$GBRANCH
      echo "I: Debian branch is: $BRANCH, set in debian/gbp.conf"
    fi
  fi
fi
if [ -z "$BRANCH" ] ; then
  BRANCH="master"
fi
if ! git rev-parse --verify "$BRANCH" 2>/dev/null ; then
  BRANCH=$(git branch | grep master | sed 's/^\* //')
  echo "I: Debian branch is: $BRANCH"
fi
git checkout --quiet "$BRANCH"
tmppull=$(mktemp "/tmp/$(basename "$0").XXXXXX")
# not all error return codes of gbp pull are critical
gbp pull --debian-branch="$BRANCH" 2>&1 | tee > "$tmppull" || true
# do not tolerate "uncommitted changes"
if grep -q 'gbp:error: You have uncommitted changes in your source tree' "$tmppull" ; then
  cat "$tmppull"
  rm "$tmppull"
  exit 1
fi
rm "$tmppull"
unset tmppull

# Checking if latest version is likely unfit to uploaded
# will continue version upgrade nonetheless but release remains at 'UNRELEASED'
blockerText=""
if dpkg-parsechangelog |sed 1,/^Changes/d|grep -E -q '(TODO|BROKEN)'; then
    blockerText=$(dpkg-parsechangelog |sed 1,/^Changes/d|grep -E -q '(TODO|BROKEN)')
fi

epoch=""
if dpkg-parsechangelog | awk '/^Version:/ {print $2}' | grep -q '^[0-9]\+:' ; then
  epoch=$(dpkg-parsechangelog | awk '/^Version:/ {print $2}' | sed 's/^\([0-9]\+:\).*/\1/')
fi
changedwatch=""
# shellcheck disable=SC2016
if [ -e debian/watch ] ; then
  if grep -E -q "https://github.com.*archive/" debian/watch; then
    echo -n "I: github watch file still expects 'archive' in path ..."
    sed -i '/https:..github.com/s%\(https://github.com.*\) .*archive%\1 .*%' debian/watch
    watchchanged=$(git diff debian/watch)
    if [ "$watchchanged" != "" ] ; then
      echo "fixed"
      echo
      echo "I: The following changes on debian/watch to respect new github layout"
      git diff debian/watch | sed -e 's/^/   /'
      echo
#set -x
      changedwatch="Fix watchfile to detect new versions on github"
      echo "$changedwatch" # somehow changedwatch is only set when this echo statement is done
      if ! grep -q "$FULLNAME" debian/control ; then
        if [ "$DIST" = "$TARGETDIST" ] ; then
          dch --team "$changedwatch" | sed -e 's/^/   /'
        fi
      else
        if [ "$changedwatch" != "" ] ; then
          dch "$changedwatch" | sed -e 's/^/   /'
        fi
      fi
      git commit -a -m"$changedwatch"
      changedwatch=""
    else
      cat <<EOT
W: The watch file is using a github address that was invalidated by a change on
   Github and needs to be fixed.  The attempt to fix the watch file automatically
   by $(basename "$0") failed.  Please set the string manually to match something
   like
     https://github.com/#GITHUBUSER#/#PACKAGE#/tags (?:.*?/)?v?(\d[\d.]*)\.tar\.gz
EOT
      exit 1
    fi
  fi

  if grep -q 'https*:$1packages/release/bioc' debian/watch ; then
    echo "I: BioConductor has changed download links thus debian/watch needs to be adapted"
    sed -i 's+?https*:$1packages/release/bioc?+?https://bioconductor.org/packages/release/bioc?+' debian/watch
    changedwatch="Fixed debian/watch for BioConductor"
  fi

  if [ "$NOUSCAN" -ne 1 ] ; then
    echo "I: Running uscan to test for new upstream releases"
    if [ "$FORCE" -ne 0 ] ; then
      set +e # even tolerate uscan errors if FORCE is set
    fi
    uscan_out=$(uscan --verbose | grep -E -A 1 -e 'Package is up to date' -e 'Newer package available from' -e '^Successfully repacked ' -e '^Leaving .* where it is' -e '^Successfully symlinked ')
    set -e
    # shellcheck disable=SC2001
    echo "$uscan_out" | sed -e 's/^/   /'
    tarball=$(echo "$uscan_out" | grep ".orig.tar."| tr " ,;" "\n" | grep ".orig.tar." | tail -n 1 | sed -e 's/\.$//')
    #echo "D: Assigned tarball '$tarball'"
    if echo "$uscan_out" | grep -E -q "^uscan.*=> Package is up to date" ; then
      tarball=""
      if [ "$FORCE" -eq 0 ] ; then
        echo
        echo "I: Package is up to date, not downloading."
        echo "   Consider pushing changes already made in $(pwd) to the archive."
        echo
        echo "I: Output of 'git status':"
        echo
        git status | sed -e 's/^/   /'
        exit 0
      fi
    fi
  else
    echo "I: Do not seek new for new upstream version, just upgrade packaging"
  fi

  if ! echo "$uscan_out" | grep -q "=> Newer package available from" ; then
    if [ "$FORCE" -eq 1 ] || [ "$NOUSCAN" -eq 1 ] ; then
      echo "I: Force packaging updates even if no new upstream version available or wanted"
      newversion=$(dpkg-parsechangelog | awk '/^Version:/ {print $2}' | sed 's/-[^-]\+$//')
      if [ "$epoch" != "" ] ; then
        newversion=${newversion/#${epoch}:/}
      fi
      if ! grep -q "$FULLNAME" debian/control ; then
        if [ "$DIST" = "$TARGETDIST" ] ; then
          dch --team "$changedwatch" | sed -e 's/^/   /'
        fi
      else
        if [ "$changedwatch" != "" ] ; then
          dch "$changedwatch" | sed -e 's/^/   /'
        fi
      fi
    else
      echo "I: No newer upstream version, not FORCEd to continue - exiting"
      exit 0
    fi
  fi

  if [ "$tarball" != "" ] ; then # there is a new upstream version and no FORCE=1 is neede[5~d
    # shellcheck disable=SC2001
    newversion=$(echo "$tarball" | sed 's/^.*_\([0-9].*\)\.orig\.tar\..*/\1/')
    if grep -q "$FULLNAME" debian/control ; then
      dch --mainttrailer --newversion "$epoch$newversion-1" 'New upstream version'
      if [ "$changedwatch" != "" ] ; then
        dch "$changedwatch"
      fi
    else
      # somehow --team and --newversion seem to conflict each other (which is not logical at all)
      # dch --team --newversion $newversion 'New upstream version'
      # This was reported here https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=851768
      if [ "$DIST" = "$TARGETDIST" ] ; then
        dch --mainttrailer --team 'New upstream version'
        if [ "$changedwatch" != "" ] ; then
          dch "$changedwatch"
        fi
      fi
      sed -i "1s/(.\+)/($newversion-1)/" debian/changelog
    fi
    git commit -a -m'routine-update: New upstream version' | sed 's/^/   /'
    if [ -e ~/.gbp.conf ] && grep -q 'debian-branch.*backports' ~/.gbp.conf ; then
      # I'm using a private script that verifies proper ~/.gbp.conf
      # for more general use I hide this a bit so everybody who
      # has no such script my_git-import-orig can run this as well
      echo "W: Suspicious debian-branch in your ~/.gbp.conf mentioning backport"
      echo "W: Please check your configuration"
      my_git-import-orig "$tarball"
    else
      gbp import-orig --debian-branch="$BRANCH" --pristine-tar --upstream-version="$newversion" --no-interactive "$tarball"
    fi
  else
    if [ "$DIST" = "$TARGETDIST" ] ; then
      if grep -q "$FULLNAME" debian/control ; then
        dch --mainttrailer -i 'Packaging update'
      else
        dch --mainttrailer --team  'Packaging update'
      fi
      git commit -a -m'routine-update: Packaging update' | sed 's/^/   /'
    fi
  fi

fi # d/watch

debpkgname=$(dpkg-parsechangelog | awk '/^Source:/ {print $2}')

InfoText=""
DHVERSION=13
if grep -q '^Maintainer:.*team@neuro.debian.net' debian/control ; then
  # Due to backports to older releases NeuroDebian is very conservative with debhelper version
  DHVERSION=10
fi
DHUPDATER=0
DO_CME_DONE=0
DEBIANCONTROL="debian/control"
if [ -e debian/control.in ] ; then
  DEBIANCONTROL="debian/control debian/control.in"
fi
# sometimes cme is lagging behing debian-policy - so we adjust Standards-Version manually first
if [ "$(grep "^Standards-Version:" debian/control | sed 's/^Standards-Version: *//')" != "$STANDARDSVERSION" ] ; then
  sed -i "s/^Standards-Version:.*/Standards-Version: $STANDARDSVERSION/" ${DEBIANCONTROL}
  dch_git_commit "Standards-Version: $STANDARDSVERSION"
  InfoText=${InfoText}$'\nStandards-Version was bumped to '"$STANDARDSVERSION"
fi
if [ -e debian/compat ] ; then
  CODEDDHVERSION=$(grep -v '^ *$' debian/compat | sed 's/ *//g')
  git rm debian/compat
  if [ "$CODEDDHVERSION" != "$DHVERSION" ] ; then
    sed -i -e "s/debhelper \+(>=.*)/debhelper-compat (= ${DHVERSION})/" -e '/^[[:space:]]\+dh-autoreconf[[:space:]]*,*[[:space:]]*$/d' -e '/^[[:space:]]\+autotools-dev[[:space:]]*,*[[:space:]]*$/d' ${DEBIANCONTROL}
    sed -i -e 's/dh-autoreconf[[:space:]]*,*//' -e 's/autotools-dev[[:space:]]*,*//' ${DEBIANCONTROL}
    sed -i -e 's/ *--with *autoreconf//' -e 's/ *--parallel//' -e 's/ *--with autotools_dev//' debian/rules
  else
    sed -i -e "s/debhelper \+(>=.*)/debhelper-compat (= ${DHVERSION})/" ${DEBIANCONTROL}
  fi
  dch_git_commit "debhelper-compat $DHVERSION"
  InfoText=${InfoText}$'\nDebhelper compat level was bumped to '"$DHVERSION"
else
  if grep -q debhelper-compat debian/control ; then
    CODEDDHVERSION=$(grep debhelper-compat debian/control | sed 's/^.*debhelper-compat[[:space:]]*([=>< ]\+\([0-9]\+\)[ )]*.*$/\1/')
    if [ "$CODEDDHVERSION" != "$DHVERSION" ] ; then
      sed -i -e "s/debhelper-compat \+(=.*)/debhelper-compat (= ${DHVERSION})/" -e '/^[[:space:]]\+dh-autoreconf[[:space:]]*,*[[:space:]]*$/d' -e '/^[[:space:]]\+autotools-dev[[:space:]]*,*[[:space:]]*$/d' ${DEBIANCONTROL}
      sed -i -e 's/dh-autoreconf[[:space:]]*,*//' -e 's/autotools-dev[[:space:]]*,*//' ${DEBIANCONTROL}
      sed -i -e 's/ *--with *autoreconf//' -e 's/ *--parallel//' -e 's/ *--with autotools_dev//' debian/rules
      dch_git_commit "debhelper-compat $DHVERSION"
      InfoText=${InfoText}$'\nDebhelper compat level was bumped to '"$DHVERSION"
    fi
  else
    echo "E: debian/compat is missing and no Build-Depends debhelper-compat - no idea what to do ... exiting"
    exit 1
  fi
fi
if [ "$CODEDDHVERSION" = "$DHVERSION" ] && [ -e debian/compat ] ; then # check whether debhelper >= 11~ is set if debian/compat exists and is set to 12
  if ! grep -q "debhelper \+(>= \+${DHVERSION}" debian/control ; then
    echo "W: debian/compat is set to $DHVERSION, but debhelper has no correct versioned Build-Depends."
    sed -i -e "s/debhelper \+(>= .*)/debhelper (>= ${DHVERSION}~)/" ${DEBIANCONTROL}
    dch_git_commit "debhelper $DHVERSION"
    InfoText=${InfoText}$'\nDebhelper compat level was bumped to '"$DHVERSION"
    CODEDDHVERSION=${DHVERSION}
  fi
fi

if echo "$debpkgname" | grep -q -e "^r-cran" -e "^r-bioc" ; then
  dhrdpkgversion=$(apt-cache policy dh-r | grep '^ \*\*\*' | sed 's/^ \*\+ *\([^ ]\+\) [0-9]\+/\1/')
  if dpkg --compare-versions "$dhrdpkgversion" lt $dhrneededversion ; then
    echo "E: System need at least dh-r version $dhrneededversion but has only version $dhrdpkgversion"
    exit 1
  fi
  dh-update-R
  # Revert possibly useless versioned Build-Depends
  do_cme
  DO_CME_DONE=1
  if [ "$(git diff)" != "" ] ; then
    COMMITMSG="Autogenerated changes by routine-update\n\n"
    if git diff debian/control | grep -q '^+Maintainer:' ; then
      if git diff debian/control | grep -q '^+Uploaders:' ; then
        dch_git_commit "Reorder sequence of d/control fields by cme"
      else
        dch "Maintainer: Debian R Packages Maintainers <r-pkg-team@alioth-lists.debian.net> (routine-update)"
        COMMITMSG="$COMMITMSG\nMaintainer: Debian R Packages Maintainers <r-pkg-team@alioth-lists.debian.net>"
        DHUPDATER=1
      fi
    fi
    if git diff debian/control | grep -q '^+Vcs' ; then
      dch "Point Vcs fields to salsa.debian.org (routine-update)"
      COMMITMSG="$COMMITMSG\nPoint Vcs fields to salsa.debian.org"
      DHUPDATER=1
    fi
    if git diff debian/control | grep -q '^+Standards-Version' ; then
      dch "Standards-Version: $STANDARDSVERSION (routine-update)"
      COMMITMSG="$COMMITMSG\nStandards-Version: $STANDARDSVERSION"
      DHUPDATER=1
    fi
    if git diff debian/control | grep -q '^-#' ; then # manual intervention if comments were removed
      git diff
      read -rp "dh-update-R has removed some comments from debian/control.  Please fix manually and confirm here to continue." res
      case $res in
          ''|[YyJj]* )
		    echo "I: Continuing $(basename "$0")"
                    ;;
          *)
                    echo "W: Please inspect the diff manually"
                    exit 1
                    ;;
      esac
    fi
    if [ "$(git diff)" = "" ] ; then
      echo "debian/control was not changed"
    else
      if git diff debian/control | grep -v -e '^[-+]Maintainer ' -e '^[+-]Vcs-' -e '^[+-]Standards-Version' | grep -q '^+[^+]'; then # if there are more changes than Maintainer, Vcs or Standards-Version fields
        if git diff debian/control | grep -v -e '^[-+]Maintainer ' -e '^[+-]Vcs-' -e '^[+-]Standards-Version' | grep -q '^+[^+]'; then # if there are more changes than Maintainer, Vcs or Standards-Version  fields
          dch_git_commit "dh-update-R to update Build-Depends"
          DHUPDATER=1
        fi
      else
        if [ "$COMMITMSG" != "" ] ; then
          git commit -a -m"$COMMITMSG"
        fi
      fi
      if [ "$(git diff)" != "" ] ; then
        if [ $DEBUG -eq 1 ] ; then
          echo "Debug: somehow there are remaining diffs *****************************************"
        fi
        # for some very strange reason some changes are not commited here, just try again
        dch_git_commit "dh-update-R to update Build-Depends (2)"
        DHUPDATER=1
      fi
    fi
  fi
  else
    if grep -q "^Maintainer: \+Debian Science Team"  debian/control ; then
      sed -i 's/Debian Science Team/Debian Science Maintainers/' ${DEBIANCONTROL}
      dch_git_commit "Fix Maintainer name of Debian Science team"
    fi
##  THIS IS SIMPLY WRONG - leave the code here to always remember that maintainer address should not be changed
#else
#  if grep -q debian-med-packaging@lists.alioth.debian.org debian/control ; then
#    sed -i 's/debian-med-packaging@lists.alioth.debian.org/debian-med-packaging@alioth-lists.debian.net/' debian/control
#    dch "Fix maintainer address of Debian Med team"; git commit -a -m"Fix maintainer address of Debian Med team"
#  else if grep -q debian-science-maintainers@lists.alioth.debian.org debian/control ; then
#    sed -i 's/debian-science-maintainers@lists.alioth.debian.org/debian-science-maintainers@alioth-lists.debian.net/' debian/control
#    dch "Fix maintainer address of Debian Science team"; git commit -a -m"Fix maintainer address of Debian Science team"
#  else if grep -q debichem-devel@lists.alioth.debian.org debian/control ; then
#    sed -i 's/debichem-devel@lists.alioth.debian.org/debichem-devel@alioth-lists.debian.net/' debian/control
#    dch "Fix maintainer address of Debichem team"; git commit -a -m"Fix maintainer address of Debichem team"
#  else if grep -q @lists.alioth.debian.org debian/control ; then
#    echo "Maintainer address points to old Alioth list.  This needs to be fixed."
#    exit
#  fi
#  fi
#  fi
#  fi
fi

if [ $DO_CME_DONE -eq 0 ] ; then
  do_cme
fi

if grep -q -e '^[[:space:]]*http://cran.*r-project' -e '^[[:space:]]*http://.*bioconductor' debian/watch ; then
  sed -i -e 's#cran\.[a-z][a-z]\.r-project\.org#cran.r-project.org#' -e 's#http://#https://#' debian/watch
  dch_git_commit "Secure URI in watch file"
fi
if echo "$debpkgname" | grep -q -e "^r-cran" -e "^r-bioc" -e "^r-other" ; then
  if ! grep -q 'Testsuite: \+autopkgtest-pkg-r' debian/control ; then
    sed -i 's/^Section: .*/&\nTestsuite: autopkgtest-pkg-r/' ${DEBIANCONTROL}
    dch_git_commit "Testsuite: autopkgtest-pkg-r"
  fi
fi
if grep "^Section: " debian/control | head -n1 | grep -q "python" ; then
  if [ ! -e debian/tests/control ] ; then
    if ! ( grep -q '^Testsuite: \+autopkgtest-pkg-python' debian/control || grep -q '^Testsuite: \+autopkgtest-pkg-pybuild' debian/control ) ; then
      sed -i 's/^Section: .*/&\nTestsuite: autopkgtest-pkg-python/' ${DEBIANCONTROL}
      dch_git_commit "Testsuite: autopkgtest-pkg-python"
    fi
  fi
fi
if grep -q "^Maintainer:.*lists" debian/control ; then # if team maintenance
  if ! grep '^Vcs' debian/control ; then
    echo "E: Somehow Vcs fields vanished from debian/control."
    exit 1
  fi
    if grep "anonscm.debian.org/" debian/control ; then
      echo "E: Vcs fields keep on mentioning anonscm.debian.org"
      exit 1
    fi
fi
if echo "$debpkgname" | grep -q -e "^r-cran" -e "^r-bioc" ; then
  if grep -q "^Maintainer:.*lists" debian/control ; then # if team maintenance
    if grep -q "salsa.debian.org/med-team/r-" debian/control ; then
      echo "E: Somehow med-team is referenced which should not happen for R packages"
      exit 1
    fi
    if grep -q "salsa.debian.org/science-team/r-" debian/control ; then
      echo "E: Somehow science-team is referenced which should not happen for R packages"
      exit 1
    fi
  fi
fi

if head -n1 debian/copyright | grep -q '^Format:[[:space:]]http://' ; then
    sed -i '1s/^Format:[[:space:]]http:/Format: https:/' debian/copyright
    dch_git_commit "Secure URI in copyright format" 
fi

if grep -A2 "^get-orig-source" debian/rules | grep -q "^[[:space:]]\+uscan" ; then
    sed -i '/^get-orig-source/,/^[[:space:]]\+uscan/d' debian/rules
    dch_git_commit "Drop useless get-orig-source target"
fi

if grep -q "Joey Hess and Craig Small" debian/rules ; then
    read -rp "Please remove 'Joey Hess and Craig Small' boilerplate from debian/rules and press RET here once ready" res
    dch_git_commit "Remove old boilerplate from debian/rules"
fi

for cfile in changelog control compat copyright rules ; do
    if [ -e debian/${cfile} ] && grep -q '[[:space:]]\+$' debian/${cfile} ; then
        sed -i 's/[[:space:]]\+$//' debian/${cfile}
        dch_git_commit "Remove trailing whitespace in debian/${cfile}" 
    fi
done

if grep -q "dpkg-parsechangelog" debian/rules ; then
    sed -i -e '/dpkg-parsechangelog/I iinclude /usr/share/dpkg/default.mk' \
           -e 's/(DEBVERS)/(DEB_VERSION)/g' \
           -e 's/(DEBPKGNAME)/(DEB_SOURCE)/g' \
           -e 's/(PACKAGE)/(DEB_SOURCE)/g' \
           -e 's/(pkg)/(DEB_SOURCE)/g' \
           -e 's/(PK)/(DEB_SOURCE)/g' \
         debian/rules
    read -rp "debian/rules is parsing d/changelog.  I've just added default.mk - please fix remaining things manually and press RET here once ready" res
    dch_git_commit  "Do not parse d/changelog"
fi

if grep -q "^X-Python-Version" debian/control ; then
    sed -i '/^X-Python-Version/d' ${DEBIANCONTROL}
    dch_git_commit "Drop ancient X-Python-Version field"
fi

if grep -q "python-sphinx" debian/control ; then
    sed -i 's/python-sphinx\([ ,]\)/python3-sphinx\1/' ${DEBIANCONTROL}
    if [ "$(git diff debian/control)" != "" ] ; then
      dch_git_commit "Build-Depends: s/python-sphinx/python3-sphinx/"
    fi
fi

# Lintian bug: https://bugs.debian.org/953391
# Lintian-brush bug: https://bugs.debian.org/953736
if grep -q "dh-python" debian/control ; then
#   dh-sequence needs at least debhelper 12, so let's simplify the check
#   to the present of "debhelper-compat"
    if grep -q "debhelper-compat" debian/control ; then
#       Complex "dh $@" lines need a better way to remove the "--with python3" part
#       For now, only do the automatic replacement for simple cases
#       if grep -q -e "dh $@.*--with.*python3" debian/rules ; then
        if grep -q 'dh $@ --with python3' debian/rules ; then
            sed -i 's/dh-python/dh-sequence-python3/' ${DEBIANCONTROL}
            sed -i 's/dh $@ --with python3\,\( *[^ ]\+\) /dh $@ --with \1 /' debian/rules
            sed -i 's/dh $@ --with python3/dh $@/' debian/rules
            dch_git_commit "Build-Depends: s/dh-python/dh-sequence-python3/"
        fi
    fi
fi

if [ -e debian/pycompat ] ; then
    git rm debian/pycompat
    dch_git_commit "remove outdated debian/pycompat"
fi

if [ -e debian/tests/control.autodep8 ] && [ ! -e debian/tests/control ] ; then
    git mv debian/tests/control.autodep8 debian/tests/control
    dch_git_commit "rename debian/tests/control.autodep8 to debian/tests/control"
fi

if [ -e debian/NEWS.Debian ] && [ ! -e debian/NEWS ] ; then
    git mv debian/NEWS.Debian debian/NEWS
    dch_git_commit "rename debian/NEWS.Debian debian/NEWS"
fi

if grep -q "ADTTMP" debian/tests/run-unit-test ; then
    sed -i 's/ADTTMP/AUTOPKGTEST_TMP/g' debian/tests/run-unit-test
    dch_git_commit "autopkgtest: s/ADTTMP/AUTOPKGTEST_TMP/g"
fi

for team in $SALSACIYAMLTEAMS ; do
  # Add debian/salsa-ci.yml only if in positiv list SALSACIYAMLTEAMS (see bug #1040500)
  if grep -q "^Maintainer:.* $team" debian/control ; then
    if [ ! -e debian/salsa-ci.yml ] && [ ! -e debian/gitlab-ci.yml ] && [ ! -e debian/.gitlab-ci.yml ] ; then
      cat > debian/salsa-ci.yml <<EOT
---
include:
  - https://salsa.debian.org/salsa-ci-team/pipeline/raw/master/salsa-ci.yml
  - https://salsa.debian.org/salsa-ci-team/pipeline/raw/master/pipeline-jobs.yml
EOT
      git add debian/salsa-ci.yml
      dch_git_commit "Add salsa-ci file"
    fi
  fi
done

if echo "$debpkgname" | grep -q -e "^r-bioc" ; then
  if ! grep -q 'piuparts:' debian/salsa-ci.yml ; then
    cat >> debian/salsa-ci.yml <<EOT

# Reduce piuparts noise in transitions
piuparts:
  allow_failure: true
EOT
    dch_git_commit "Reduce piuparts noise in transitions"
  fi
fi

if ! grep -q Rules-Requires-Root: debian/control ; then
   sed -i 's/^Homepage: .*/&\nRules-Requires-Root: no/' ${DEBIANCONTROL}
   dch_git_commit "Rules-Requires-Root: no"
fi

if grep -q -P '\t' debian/copyright ; then
   sed -i 's/\t/        /g' debian/copyright
   dch_git_commit "No tab in license text"
fi

LIBRUSH=$(lintian-brush 2>&1 | head -n1)
if [ "$LIBRUSH" != "No changes made." ]; then
    echo "I: lintian-brush was doing some changes"
fi

AMHINTS=$(apply-multiarch-hints 2>&1 | head -n1)
if [ "$AMHINTS" != "Nothing to do." ]; then
    echo "I: apply-multiarch-hints was doing some changes"
fi

DSOBSOLETE=$(deb-scrub-obsolete 2>&1 | wc -l)
if [ "$DSOBSOLETE" -gt 1 ]; then
    echo "I: deb-scrub-obsolete was doing some changes"
fi

if [ -e debian/control.in ] ; then
  if grep -q "^debian/control:" debian/rules ; then
    # check whether janitor tools might have changed debian/control
    # it is assumed that the variables that will be replaced contain @-signs
    if [ $(diff -u0 debian/control.in debian/control | grep -v -e '^---' -e '^+' -e '@' | wc -l) -eq 0 ] ; then
      # seems debian/control was not changed
      touch debian/control.in
      make -f debian/rules debian/control
      dch_git_commit "Regenerate debian/control from debian/control.in"
    else
      echo "There are some changes in debian/control which are not reflected in debian/control.in"
      echo "Please fix this manually."
      exit
    fi
  else
    echo "There is a debian/control.in file but debian/rules does not contain any debia/control target"
    echo "Since this is suspicious I stop here and leave everything else to you."
    exit
  fi
fi

if [ "" != "$blockerText" ]; then
    echo "E: Changelog contains TODO/Blocker note - not setting release to '$TARGETDIST'. Please inspect and fix."
    echo
    echo "$blockerText"
    echo
    # in the likely case that a new version was created, forward the blocker text
    if ! dpkg-parsechangelog | sed 1,/^Changes/d| grep -q -E '(TODO|BLOCKER)'; then
       echo "I: Forwardiong blocker text to current version"
       dch --apend "$blockerText"
    fi
    exit 1
fi

if [ -d debian/tests ] ; then
    if grep -q '#PACKAGENAME#' debian/tests/* ; then
        read -rp '   Autopkgtest script has #PACKAGENAME# boilerplate. Please use another terminal to fix the test and press RET here once ready' res
    fi
fi

if grep -q 'version[[:space:]]*=[[:space:]]*[123]' debian/watch ; then
   sed -i 's/\(version[[:space:]]*=[[:space:]]*\)[123]/\14/' debian/watch
   dch_git_commit "watch file standard 4"
fi

if [ -e debian/patches/series ] ; then
  if [ "$(grep -v -c -e '^#' -e '^[[:space:]]*$' debian/patches/series)" -gt 0 ] ; then # some series files are comments only - no need to test that patches
    tmpquilt=$(mktemp /tmp/quilt.XXXXXX)
    if ! quilt push -a >> "$tmpquilt"; then
      echo "E: Could not apply patches:"
      cat "$tmpquilt"
      rm -f "$tmpquilt"
      exit 1
    fi
    quilt pop -a
    if grep -q "Hunk .* succeeded .* with fuzz" "$tmpquilt" ; then
      echo "W: There is fuzz in some patches."
      read -rp "   Please use another terminal to inspect patches and press RET here once ready" res
    fi
    rm -f "$tmpquilt"
    rm -rf .pc
    unset tmpquilt
  fi
fi

dch -r '' --distribution $TARGETDIST
if [ "$BUILDPACKAGE" -eq 1 ]; then
	/usr/bin/gbp buildpackage --git-debian-branch="$BRANCH" --git-ignore-new
	echo "I: Build was successful."
fi
git commit -a -m"routine-update: Ready to upload to $TARGETDIST"

if ! LC_ALL=C git status | grep -q "working tree clean"; then
  echo "I: Repository is not clean after build. Running 'debian/rules clean' to remove leftover build files. "
  echo "   Somehow magically fix your gbp.conf to build with cowbuilder, i.e. outside this repository."
  fakeroot ./debian/rules clean | sed -e 's/^/   /'

  if ! LC_ALL=C git status | grep -q "working tree clean"; then
    echo "E: Repository is still not clean. Cannot tag current state. "
    echo "   Please fix cleaning in debian/rules and then run 'gbp tag' prior to push."
    exit 1
  fi

fi
if [ "$NOTAG" != 1 ]; then
  echo "I: setting git tags"
  gbp tag --debian-branch="$BRANCH" | sed -e 's/^/   /'
fi
echo "I: The update was successful. You may now want to"
if [ -n "$changingDirectoryTo" ]; then
  echo "     pushd $changingDirectoryTo"
fi
echo "     git push --all"
if [ "$NOTAG" = 1 ]; then
  echo "I: then upload and finally tag the release:"
  echo "     gbp tag --debian-branch=\"$BRANCH\""
fi
echo "     git push --tags"
if [ -n "$changingDirectoryTo" ]; then
  echo "     popd"
fi
if [ "${InfoText}" != "" ] ; then
  echo "I: The following potentially breaking changes were done. Please be careful."
  echo "${InfoText}"
  echo
fi
