#!/bin/bash

if [ -d squashfs-root ]; then
  rm -rf squashfs-root
fi

if ! [ -e Lagrange.AppImage ]; then
  curl -L -o Lagrange.AppImage \
    https://git.skyjake.fi/gemini/lagrange/releases/download/v1.18.4/Lagrange-1.18.4-x86_64.AppImage || die "cannot fetch lagrange"
  chmod +x Lagrange.AppImage
fi

if ! [ -e appimagetool.AppImage ]; then
  curl -L -o appimagetool.AppImage \
    https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage || dir "cannot fetch appimagetool"
  chmod +x appimagetool.AppImage
fi

./Lagrange.AppImage --appimage-extract

VERSION=$(./target/release/caracal -V|awk '{print $2}')

cp target/release/caracal squashfs-root/usr/bin

rm squashfs-root/AppRun

cat << \EOF > squashfs-root/AppRun
#!/bin/bash

HERE=$(dirname $(readlink -f "${0}"))
PIDFILE="/tmp/caracal-lagrange.pid"
PORT=1985

${HERE}/usr/bin/caracal -p $PORT --pid-file $PIDFILE &

${HERE}/usr/bin/lagrange "gemini://localhost:$PORT" "$@"

if [ -e $PIDFILE ]; then
  kill -HUP $(cat $PIDFILE)
fi
EOF

chmod 755 squashfs-root/AppRun

ARCH="x86_64" ./appimagetool.AppImage squashfs-root/ caracal-$VERSION-x86_64.AppImage
