#!/usr/bin/env dash
# https://nochlin.com/blog/6-techniques-i-use-to-create-a-great-user-experience-for-shell-scripts
# via https://news.ycombinator.com/item?id=41512899
set -u
set -e
cd "$(dirname "$0")"

[ "$1" = "" ] && {
cat << EOF
Give me a git sha or source tar to mint a release from.
EOF

  exit 0
}

pk_pem="$(ls /media/*/seppo.priv.pem 2>/dev/null)" ; readonly pk_pem
wd="/var/spool/build/src/seppo" ; readonly wd
emu="$(sysctl compat.linux.emul_path | cut -d : -f 2 | tr -d ' ')" ; readonly emu
ls -d "$emu$wd" > /dev/null

src="$(dirname "$emu$wd")/source.tar.gz" ; readonly src
GIT_SHA="-"
set +e
if tar tzf "$1" > /dev/null 2>&1
then
  cp -p "$1" "$src"
else
  GIT_SHA="$1"
  echo "curl -LO https://codeberg.org/seppo/seppo/archive/$GIT_SHA.tar.gz"
  curl \
    --output "$src" \
    --location "https://codeberg.org/seppo/seppo/archive/$GIT_SHA.tar.gz"
fi
set -e
tar tzf "$src" > /dev/null

echo "one source to build them all"
ls -l "$src"
# echo "$emu$wd"
rm -rf "${emu:?}$wd/"
tar xzf "$src" -C "$(dirname "$emu$wd")"

uname -sm | figlet
opam switch
echo "GIT_SHA=$GIT_SHA gmake -C $emu$wd clean test final"
GIT_SHA="$GIT_SHA" gmake -C "$emu$wd" clean test final
echo ""
cat <<EOF > "$emu$wd/chroot.make.sh"
uname -sm | figlet
opam switch
cd
rsync -qaP --delete --exclude _build "$wd" .
echo "GIT_SHA=$GIT_SHA make -C seppo "\$@""
GIT_SHA="$GIT_SHA" make -C seppo "\$@"
EOF
echo "doas chroot $emu su - $USER -c \"GIT_SHA=$GIT_SHA sh $wd/chroot.make.sh clean test final\""
doas chroot "$emu" su - "$USER" -c "GIT_SHA=$GIT_SHA sh $wd/chroot.make.sh clean test final"
echo ""

set +v
echo "collect results"
cd "$emu$wd/_build"
pwd
rsync -aP "$src" "$emu$HOME/seppo/_build/"*.cgi .
# should this go into Makefile?
ver="$(grep -hoE "^\(version [^\)]+" ../dune-project | cut -d ' ' -f2)"
date="$(date)"
readonly ver date
export ver date GIT_SHA 
envsubst < ../README.txt.tpl > README.txt

curl \
  --output "www.tar.gz" \
  --location "https://codeberg.org/seppo/www/archive/ma.tar.gz"

echo "sign binaries"
for f in README.txt *.cgi source.tar.gz www.tar.gz
do
  # https://stackoverflow.com/a/18359743
  openssl dgst -sha256 -sign "$pk_pem" -out "$f.signature" "$f"
done
ls -Al *.signature

dst="seppo-${ver}_$(date +%Y%m%d).tar.gz"
readonly dst
tar czf "$dst" -- README.txt* *.cgi* source.tar.gz* www.tar.gz*
tar tzf "$dst"
ls -l "$(pwd)/$dst"
