#!/usr/bin/env dash
set -e
cd "$(dirname "$0")"

readonly wd="/var/spool/build/src/seppo"

uname -sm | figlet
opam switch
[ "$1" = "inside" ] && {
  shift
  cd
  rsync -qaP --delete --exclude _build --exclude doc "$wd" .
  # just be explicit:
  echo "GIT_SHA=$GIT_SHA make -C seppo $*"
  GIT_SHA=$GIT_SHA make -C seppo "$@"

  exit
}

emul_path="$(sysctl compat.linux.emul_path | cut -c25-)"
readonly emul_path
ls -d "$emul_path$(dirname "$wd")" > /dev/null

pwd
echo "rsync -qaP --delete --exclude _build --exclude .git . $emul_path$wd"
rsync -qaP --delete --exclude _build --exclude .git . "$emul_path$wd"

GIT_SHA="$(git log -1 --format="%h")"
echo "GIT_SHA=$GIT_SHA gmake -C $emul_path$wd $*"
GIT_SHA=$GIT_SHA gmake -C "$emul_path$wd" "$@"
echo ""
echo "doas chroot $emul_path su - $USER -c \"GIT_SHA=$GIT_SHA sh $wd/$(basename "$0") inside $*\""
doas chroot "$emul_path" su - "$USER" -c "GIT_SHA=$GIT_SHA sh $wd/$(basename "$0") inside $*"
echo ""

echo collect binaries
cd "$emul_path$wd/_build"
pwd
rsync -aP "$emul_path$HOME/seppo/_build/"*.cgi .
tar czf source.tar.gz --exclude _build ..

echo sign binaries
pk_pem="$(ls /media/*/*/seppo.priv.pem 2>/dev/null)"
readonly pk_pem
for f in *.cgi source.tar.gz
do
  # https://stackoverflow.com/a/18359743
  # echo "openssl dgst -sha256 -sign $pk_pem -out $f.signature $f"
  openssl dgst -sha256 -sign "$pk_pem" -out "$f.signature" "$f"
done
ls -l ./*.signature

echo deploy
for dst in dev.seppo.mro.name
do
  echo "$dst" | figlet
  arch="$(ssh -4 "$dst" uname -sm | tr ' ' '-')"
  rsync -4 -avPz -- *"-$arch"-*.cgi* "$dst":~/mro.name/dev.seppo/ || {
    beep ; beep ; beep
    continue
  }

  f="$(ls -t "seppo-$arch"-*.cgi | head -n 1)"
  ssh -4 "$dst" "cd mro.name/dev.seppo && rm seppo.cgi ; ln -s $f seppo.cgi"
done

beep
