#!/bin/bash

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

usage() {
  >&2 echo 'usage:'
  >&2 echo '  bumpPython 2 [$version]'
  >&2 echo 'or:'
  >&2 echo '  bumpPython 3 [$version]'
  exit 1
}

if [ $# -ne 1 ] && [ $# -ne 2 ]; then
  usage
fi

case "$1" in

  '2')
    pkgbuilds=(
      $(grep -l 'python>=2' */PKGBUILD)
    )
    if [ $# -eq 1 ]; then
      pyver=$(
        python2 --version 2>&1
      )
    else
      pyver="$2"
    fi
  ;;
  '3')
    pkgbuilds=(
      $(grep -l 'python>=3' */PKGBUILD)
    )
    if [ $# -eq 1 ]; then
      pyver=$(
        python --version 2>&1
      )
    else
      pyver="$2"
    fi
  ;;
  *)
    usage
  ;;
esac

pyver=$(
  printf '%s\n' "${pyver}" | \
    cut -d' ' -f2 | \
    cut -d. -f1,2
)
pymajor="${pyver%%.*}"
pyverupper="${pymajor}.$((${pyver#*.}+1))"

for pkgbuild in "${pkgbuilds[@]}"; do

  ./bumpPkgrel -n "${pkgbuild%/PKGBUILD}"
  sed -i '
    s@'"'python>=${pymajor}\.[0-9]\+'@'python>=${pyver}'"'@
    s@'"'python<${pymajor}\.[0-9]\+'@'python<${pyverupper}'"'@
  ' "${pkgbuild}"
  cd "${pkgbuild%/*}"
  ../commit-package
  cd ..

done

git commit -m 'recompile all python packages'