#!/bin/bash

me="$(readlink -f "$0")"
myDir="$(dirname "${me}")"

verwendung() {
  >&2 echo ''
  >&2 echo "$(basename "$0")"': aktualisiere Version von Paketen in archlinuxewe'
  >&2 echo ''
  >&2 echo 'mögliche Optionen:'
  >&2 echo '  -f|--force:            übergehe Cache'
  >&2 echo '  -h|--help:             zeige diese Hilfe'
  >&2 echo '  -n|--nicht $paket:     ignoriere Paket $paket'
  >&2 echo '  -p $tmpfile:           temporäre "provided"-Datei'
  [ -z "$1" ] && exit 1 || exit $1
}

check_version_cache_option=''

eval set -- "$(
  getopt -o fhn:p: \
    --long force \
    --long help \
    --long nicht: \
    -n "$(basename "$0")" -- "$@" || \
    echo verwendung
)"

unset nichtPakete
unset provided

while true; do
  case "$1" in
    -h|--help)
      verwendung 0
    ;;
    -f|--force)
      check_version_cache_option='--no-cache'
    ;;
    -n|--nicht)
      shift
      nichtPakete="$(printf '%s\n%s' "${nichtPakete}" "$1" | grep -v '^$')"
    ;;
    -p)
      shift
      provided="$1"
    ;;
    --)
      shift
      break
    ;;
    *)
      >&2 echo 'Hups, das sollte nicht passieren können, Option '"$1"' kenne ich doch nicht ...'
      exit -1
  esac
  shift
done

if [ $# -eq 0 ]; then
  >&2 echo 'bumping versions of all packages ...'
  pkgs="$(
    (
      "${myDir}/checkVersions" --noUpdate | \
        cut -d: -f1
      echo "${nichtPakete}"
      echo "${nichtPakete}"
    ) | \
      sort | \
      uniq -u
  )"
  [ -z "${pkgs}" ] && exit 0
  if [ -z "${provided}" ]; then
    provided=$("${myDir}/liste-verfuegbare-Versionen")
    trap 'rm -f "${provided}"' EXIT
  fi
  "${me}" -p "${provided}" ${pkgs}
  exit $?
elif [ $# -gt 1 ]; then
  [ -n "${nichtPakete}" ] && verwendung
  if [ -z "${provided}" ]; then
    provided=$("${myDir}/liste-verfuegbare-Versionen")
    trap 'rm -f "${provided}"' EXIT
  fi
  err=0
  for pkg in "$@"; do
    "${me}" -p "${provided}" "${pkg}"
    cErr=$?
    [ ${cErr} -gt ${err} ] && err=${cErr}
  done
  exit ${err}
fi
[ -n "${nichtPakete}" ] && verwendung

if [ -z "${provided}" ]; then
  provided=$("${myDir}/liste-verfuegbare-Versionen")
  trap 'rm -f "${provided}"' EXIT
fi

paket="${1%/}"
>&2 echo "bumping '${paket}' ..."

cd "${myDir}"
[ -r "${paket}/PKGBUILD" ] || exit 1
if ! vers="$(./checkVersions -m "${paket}" ${check_version_cache_option})"; then
  >&2 echo 'checkVersion returned non-zero'
  exit 1
fi
[ -n "${remVer}" ] && vers="$(echo "${vers}" | grep -v 'remVer')"
eval ${vers}
if [ "${remVer}" == "${pkgver}" ]; then
  >&2 echo '... nothing to do here.'
  exit 0
fi

if [ -z "${remVer}" ]; then
  >&2 echo '... remote Version not determined.'
  exit 0
fi

# Wir misbrauchen bumpPkgrel um _pinned_dependencies zu aktualisieren.
# $pkgrel wird nachher ohnehin wieder auf 1 gesetzt.
"${myDir}/bumpPkgrel" -n -p "${provided}" "${paket}"

auto_summen=true

cd "${paket}"

if [ "${paket}" = 'local-certificates' ]; then
  sums=$(
    curl -Ss 'https://eckner.net/certs/sha512sums'
  )
  sed_extra='
    /^source=/ i source=(\
'"$(
      printf '%s\n' "${sums}" \
      | sed '
        s@^\S\+  @  '"'"'https://eckner.net/certs/@
        s/$/'"'"'\\/
      '
    )"'
)\
sha512sums=(\
'"$(
      printf '%s\n' "${sums}" \
      | sed '
        s/  .*$/'"'"'\\/
        s/^/  '"'"'/
      '
    )"'
)
    /^source=/,/)$/ d
    /^sha512sums=/,/)$/ d
  '
  auto_summen=false
elif [ "${paket}" = 'otf-grundschrift' ]; then
  md5sum=$(
    curl -LSs 'https://fontlibrary.org/en/font/grundschrift' \
    | sed '
      s@^.*<a href="/assets/downloads/grundschrift/\([0-9a-f]\{32\}\)/grundschrift\.zip" .*$@\1@
      t
      d
    '
  )
  sed_extra='
    s@^\s*md5sums=(\S\+).*$@md5sums=('"'${md5sum}'"')@
'
  auto_summen=false
fi

sed -i 's|^\(\s*\)pkgver=.*$|\1pkgver='"${remVer}"'|;
  s|^\(\s*\)pkgrel=.*$|\1pkgrel=1|;
  '"${sed_extra}"'
' PKGBUILD

if ${auto_summen}; then
  sed -i '
    s@^\s*\(sha[[:digit:]]\+sums\|md5sums\)=@sha512sums=@;
    /^\(sha[[:digit:]]\+\|md5\)sums_/d;
  ' PKGBUILD

  sed '
    :begin;
      $!N;
      s@^sha512sums=\([^)]*\)\n\(.*\)$@sha512sums=\1 \2@;
    tbegin;
    P;
    D
  ' -i PKGBUILD

  summen="$( \
    makepkg -g | \
      sed ':begin;
          $!N;
          s@^\(.*\)\n\(.*\)$@\1\\n\2@;
        tbegin;
        P;
        D
      ' \
  )"
  sed 's|sha512sums=.*$|'"${summen}"'|' -i PKGBUILD
fi

(
  if ! yes '' | "${myDir}/testeAbhaengigkeiten" "${paket}"; then
    was=''
    ec[0]='jJyY'
    ec[1]='nN'
    while [[ "${ec[0]}" != *"${was}"* ]] && [[ "${ec[1]}" != *"${was}"* ]] || [ -z "${was}" ]; do
      read -p 'Trotzdem weiter machen (j/y/n)? ' was
    done
    [[ "${ec[0]}" == *"${was}"* ]]
  fi
) || exit $?

if [ "${paket}" != 'qgis-git' ]; then
  rm -rf "src" "pkg"
  sudo pacman -Sy
  makepkg -fcsr --noconfirm --asdeps || exit 1
  for pkg in $(makepkg --packagelist); do
    namcap "${pkg}" || exit 1
  done
fi
../commit-package "${paket} ${pkgver}-${pkgrel} -> ${remVer}-1"

>&2 echo '... done'