#!/bin/sh

set -e -C

usage="usage: pack.sh app.scm target.run"
test -z "$1" && (echo $usage; exit 1;)
test -z "$2" && (echo $usage; exit 1;)

# Compile your source code
guild compile $1 -o app/app.scm.go

# Create a portable, uncompressed Guile tarball
cp $(guix pack -f tarball -C none -RR guile -S /bin=bin) guile.tar.gz

# Append compiled app binaries.
chmod +w guile.tar.gz
tar --append --file=guile.tar.gz app/

# Build wrapper
cat - guile.tar.gz <<'EOF'>$2
#!/bin/sh
set -e -C
offset=8
dir=$(mktemp -d)
trap 'chmod -R o+w "$dir"; rm -rf "$dir"; trap - EXIT; exit' EXIT INT HUP
tail -n +$offset $0 | tar xf - -C $dir && cd $dir; exec ./bin/guile -c '(load-compiled "app/app.scm.go")'
# append "guix pack" archive here.
EOF

chmod +x $2
