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

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

uname -sm | figlet
[ "$1" = "inside" ] && {
  shift
  echo inside $GIT_SHA
  cd
  rsync -qaP --delete --exclude _build --exclude doc "$wd" .
  make -C seppo "$@"

  exit
}

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

echo get the sources
rsync -qaP --delete --exclude _build --exclude .git . "$emul_path/$wd"

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

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

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

echo "Dev.Seppo.Social" | figlet
arch="$(ssh dev.seppo.social uname -sm | tr ' ' '-')"
rsync -avPz -- *"-$arch"-*.cgi* dev.seppo.social:~/tmp/

f="$(ls -t "seppo-$arch"-*.cgi | head -n 1)"
ssh dev.seppo.social "cd tmp && rm seppo.cgi ; ln -s $f seppo.cgi"

beep
