#!/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.

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"

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

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:
     -f|--force: also runs on projects that are up to date
     --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
BUILDPACKAGE=1
for i in "$@"
do
case $i in
    -f|--force)
    FORCE=1
    shift
    ;;
    -h|--help)
    show_help
    exit;
    ;;
    --no-build)
    BUILDPACKAGE=0
    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 [ "$1" = "clone" ] || [ "$1" = "--clone" ] ; then
  if [ -z "$2" ]; then
    echo "E: specify an URL for git to clone"
    exit 1
  fi
  gbp clone --pristine-tar "$2"
  d=$(basename "$2" .git)
  if [ ! -d "$d" ]; then
    echo "E: Internal error - git should have created directory '$d'"
    exit 1
  fi
  echo "I: Changing into directory '$d'"
  cd "$d"
  unset d
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

  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
        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

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 "Point Vcs fields to salsa.debian.org (routine-update)"
    git commit -a -m"routine-update: Point Vcs fields to salsa.debian.org"
  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
}

dch_git_commit () {
    dch "$1 (routine-update)"
    git commit -a -m"routine-update: $1"
}

gbp pull

BRANCH=master
if [ -e debian/gbp.conf ] ; then
  if grep -q "^debian-branch" debian/gbp.conf ; then
      BRANCH=$(grep "^debian-branch" debian/gbp.conf | tail -n1 | sed 's/^debian-branch[[:space:]]*=[[:space:]]*//')
    echo "I: Debian branch is: $BRANCH"
  fi
fi
if ! git rev-parse --verify "$BRANCH" 2>/dev/null ; then
 BRANCH=$(git branch | grep master | sed 's/^\* //')
fi
git checkout --quiet "$BRANCH"
tmppull=$(mktemp "/tmp/$(basename "$0").XXXXXX")
# not all error return codes of gbp pull are critical
gbp pull 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 -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
  uscan_out=$(uscan --verbose | grep -e 'Package is up to date' -e 'orig\.tar')
  tarball=$(echo "$uscan_out" | grep ".orig.tar.[bgx]z2*" | sed 's#^.* \(\.\./[^ ]*\.orig\.tar\.[bgx]z2*\).*#\1#')
  if echo "$uscan_out" | grep -q "uscan info: *=> Package is up to date" ; then
    tarball=""
  fi
  if [ "$tarball" = "" ] ; then
    if [ "$FORCE" -eq 1 ] ; then
      echo "I: Force packaging updates even if no new upstream version available"
  #    newversion=`dpkg-parsechangelog | awk '/^Version:/ {print $2}' | sed 's/-[^-]\+$//'`
  #    if [ "$epoch" != "" ] ; then
  #      newversion=`echo $newversion | sed "s/^${epoch}://"`
  #    fi
      if ! grep -q "$DEBFULLNAME" debian/control ; then
        if [ "$DIST" = "unstable" ] ; then
          dch --team "$changedwatch"
        fi
      else
        if [ "$changedwatch" != "" ] ; then
          dch "$changedwatch"
        fi
      fi
    else
      echo "E: Uscan did not return tarball name"
      exit 1
    fi
  else
    newversion=$(echo $tarball | sed 's/^.*_\([0-9].*\)\.orig\.tar\..*/\1/')
    if grep -q "$DEBFULLNAME" 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" = "unstable" ] ; 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'
    if 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 --pristine-tar --upstream-version="$newversion" --no-interactive $tarball
    fi
  fi
fi
debpkgname=$(dpkg-parsechangelog | awk '/^Source:/ {print $2}')

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
# 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/" debian/control
  dch_git_commit "Standards-Version: $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' debian/control
    sed -i -e 's/dh-autoreconf[[:space:]]*,*//' -e 's/autotools-dev[[:space:]]*,*//' debian/control
    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})/" debian/control
  fi
  dch_git_commit "debhelper-compat $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' debian/control
      sed -i -e 's/dh-autoreconf[[:space:]]*,*//' -e 's/autotools-dev[[:space:]]*,*//' debian/control
      sed -i -e 's/ *--with *autoreconf//' -e 's/ *--parallel//' -e 's/ *--with autotools_dev//' debian/rules
      dch_git_commit "debhelper-compat $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}~)/" debian/control
    dch_git_commit "debhelper $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
      dch "Maintainer: Debian R Packages Maintainers <r-pkg-team@alioth-lists.debian.net> (R-U)"
      COMMITMSG="$COMMITMSG\nMaintainer: Debian R Packages Maintainers <r-pkg-team@alioth-lists.debian.net>"
      DHUPDATER=1
    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 > /dev/null ; 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
    fi
  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/' debian/control
    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 ; then
      sed -i 's/^Section: .*/&\nTestsuite: autopkgtest-pkg-python/' debian/control
      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 "^override_dh_auto_test" debian/rules ; then
    # shellcheck disable=SC2016
    if ! grep -A1 -B1 "^override_dh_auto_test" debian/rules | grep -q -e '$(filter nocheck, *$(DEB_BUILD_OPTIONS)' -e '$(findstring nocheck, *$(DEB_BUILD_OPTIONS))' -e '$(filter nocheck,$(DEB_BUILD_PROFILES))'; then
        sed -i '/^override_dh_auto_test/a ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))' debian/rules
        read -rp "DEB_BUILD_OPTIONS was added to debian/rules:override_dh_auto_test. Please manually add 'endif' and press RET here once ready" res
        dch_git_commit "Respect DEB_BUILD_OPTIONS in override_dh_auto_test target"
    fi
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-Python3\?-Version" debian/control ; then
    sed -i '/^X-Python3\?-Version/d' debian/control
    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/' debian/control
    dch_git_commit "Build-Depends: s/python-sphinx/python3-sphinx/"
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

if [ ! -e debian/salsa-ci.yml -a ! -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

if ! grep -q Rules-Requires-Root: debian/control ; then
   sed -i 's/^Homepage: .*/&\nRules-Requires-Root: no/' debian/control
   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


if [ "" != "$blockerText" ]; then
    echo "E: Changelog contains ToDO/Blocker note - not setting release to 'unstable'. 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 unstable
## gbp-build is a private script from Andreas Tille setting some environment variables
## Try to use default gbp instead.
# gbp-build --git-ignore-new
if [ "$BUILDPACKAGE" -eq 1 ]; then
	/usr/bin/gbp buildpackage -uc -us --git-pbuilder-options="--source-only-changes" --git-ignore-new
	echo "I: Build was successful."
fi
git commit -a -m"routine-update: Ready to upload to unstable"

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

  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 clensing in debian/rules and then run 'gbp tag' prior to push."
    exit 1
  fi

fi
echo "I: settting git tags"
gbp tag
echo "I: The update was successful. You may now want to"
echo "     git push --all"
echo "     git push --tags"
