#!/usr/bin/env dash
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/msdosfs/*/seppo.priv.pem 2>/dev/null)" ; readonly pk_pem
wd="/var/spool/build/src/seppo" ; readonly wd
emul_path="$(sysctl compat.linux.emul_path | cut -d : -f 2 | tr -d ' ')" ; readonly emul_path
ls -d "$emul_path$(dirname "$wd")" > /dev/null

src="$emul_path$(dirname "$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"
  curl \
    --output "$src" \
    --location "https://codeberg.org/seppo/seppo/archive/$GIT_SHA.tar.gz"
fi
set -e
readonly GIT_SHA
export GIT_SHA
tar tzf "$src" > /dev/null
echo "a tar $(ls "$src")"

echo "one source for two builds"
rm -rf "${emul_path:?}${wd:?}/"
tar xzf "$src" -C "$emul_path/$(dirname "$wd")"

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

echo "collect results"
cd "$emul_path/$wd/_build"
rsync -aP "$src" "$emul_path/$HOME/seppo/_build/"*.cgi .
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

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

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