#!/bin/bash

series=devel
port=swi-prolog-devel
portprefix=/opt/local
branch=master

done=false
while [ $done = false ]; do
  case "$1" in
    --branch=*)	branch=$(echo $1 | sed 's/^[^=]*=//')
       shift
       ;;
    *) done=true
       ;;
  esac
done



if [ -x $portprefix/bin/gsed ]; then
  sed=$portprefix/bin/gsed
else
  sed=sed
fi

portgit=$HOME/src/macports-ports/
portfile=lang/$port/Portfile
version=$(cat VERSION)
distfile=swipl-$version.tar.gz
file=../$distfile

if [ -r $file ]; then
    size=$(wc -c < $file)
    sha256=$(openssl sha256 < $file | cut -d ' ' -f 2)
    rmd160=$(openssl rmd160 -provider legacy < $file | cut -d ' ' -f 2)

    if [ ! -d $portprefix/var/macports/distfiles ]; then 
	url="https://www.swi-prolog.org/download/$series/src/$distfile"
	sizew=$(curl -s --head "$url" | sed 's/\r$//' | grep ^content-length | cut -d ' ' -f 2)
	if [ ! "$size" = "$sizew" ]; then
	    echo "ERROR: $url has non-matching size"
	    echo "ERROR:   Expected: $size, found $sizew"
	    exit 1
	fi
    fi
else
    echo "ERROR: Could not find distfile $file"
    exit 1
fi

if [ -d $portprefix/var/macports/distfiles ]; then
  cp $file $portprefix/var/macports/distfiles/swi-prolog || exit 1
fi

echo "version: $version"
echo "size:    $size"
echo "sha256:  $sha256"
echo "rmd160:  $rmd160"

cbranch=$(git -C $portgit rev-parse --abbrev-ref HEAD)
if [ ! $branch = master -a $cbranch = $branch ]; then
  echo "Keeping branch $branch"
else
  git -C $portgit checkout $branch
  if [ $branch = master ]; then
    echo "Pulling $branch"
    git -C $portgit pull
  fi
  git -C $portgit branch -D $version >/dev/null 2>&1  || true
  git -C $portgit checkout -b $version
fi

$sed -i \
     -e "s/^\(version\s*\)[0-9].*/\1$version/" \
     -e "s/^\(revision\s*\)[0-9].*/\10/" \
     -e "s/^\(checksums\s*rmd160\s*\)[0-9a-f].*/\1$rmd160 \\\\/" \
     -e "s/^\(\s*sha256\s*\)[0-9a-f].*/\1$sha256 \\\\/" \
     -e "s/^\(\s*size\s*\)[0-9a-f].*/\1$size/" \
     $portgit/$portfile

git -C $portgit commit $portfile -m "$port: Updated to version $version"
