#!/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 tag      -- build the latest tagged 64-bit version
./$name latest   -- build the latest 64-bit version
./$name tag32    -- build the latest tagged 32-bit version
./$name latest32 -- build the latest 32-bit version
EOF
    exit 1
}

case $1 in
    latest|latest64)
        ext=_64
        TCMD=':'
        IMPTH=library
        ;;
    tag|tag64)
        ext=_64
        TCMD='git tag|tail -n 1'
        IMPTH=library
        ;;
    latest32)
        ext=
        TCMD=':'
        IMPTH=i386
        ;;
    tag32)
        ext=
        TCMD='git tag|tail -n 1'
        IMPTH=i386
        ;;
    *)
        usage
        ;;
esac

# Create the Containerfile
cat << EOF > Containerfile
FROM docker.io/$IMPTH/alpine
RUN apk update
RUN apk add git 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-x86$ext
EOF


cat << EOF > ./helper-script
#!/bin/sh
mnt=\$(podman image mount localhost/mg-static)
cp \$mnt/mg/mg-*static-x86* .
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
