#!/bin/sh

# This Makefile has been written by Han Boetes
# <hboetes@gmail.com> and is released in Public Domain.

isinpath () {
        command -v $1 >&/dev/null
}

for i in podman buildah; do
    if ! isinpath $i; then
        echo "$0: $i is a required dependency for this script" >&2
        EXIT=true
    fi
done

if [ "$EXIT" = true ]; then
    exit 1
fi

usage() {
    name=${0##*/}
    cat << EOF >&2
This script can build a static binary for mg, like this:
./$name [amd64|i386|arm64v8|arm32v7] [tag|latest]
Make sure your architecture is compatible.
EOF
    exit 1
}

case $1 in
    amd64)
        ext=$1
        ;;
    arm64v8)
        ext=$1
        ;;
    arm32v7)
        ext=$1
        ;;
    i386)
        ext=$1
        ;;
    *)
        usage
        ;;
esac

case $2 in
    latest)
        TCMD='date +latest%Y%m%d'
        ;;
    tag)
        TCMD='git tag|tail -n 1'
        ;;
    *)
        usage
        ;;
esac

# Create the Containerfile
cat << EOF > Containerfile
FROM docker.io/$ext/alpine
RUN apk upgrade
RUN apk add git libbsd-static libbsd-dev ncurses-dev musl-dev ncurses-static gcc make
RUN git clone https://github.com/hboetes/mg.git
WORKDIR mg
RUN TAG=\$($TCMD); \
    git checkout \$TAG; \
    make STATIC=1; \
    strip mg; \
    ln mg mg-\$TAG-static-$ext
EOF


cat << EOF > ./helper-script
#!/bin/sh
mnt=\$(podman image mount localhost/mg-static)
cp \$mnt/mg/mg-*static-* .
EOF
chmod 755 ./helper-script

podman image rm localhost/mg-static
buildah build -f Containerfile -t mg-static
podman unshare ./helper-script

# Clean up the mess
rm -f Containerfile helper-script
podman image rm localhost/mg-static
