#!/bin/bash

# This file will build the project from source using the buildah toolchain.
# It will create a container for the host to push up to the container repository.

NAME="flowms-storybook"
TAG=$1
VERSION=$(git tag | sort -nr | awk 'NR==1{print $1}')
COMMIT=$(git log --oneline --max-count=1 | cut -d ' ' --fields=1)

function help {
    echo "HELP:"
    echo "build.sh [bool]  Give true or false as a string to use the git tag"
    exit 0
}

if [ "$1" = "help" ]
then
    help
fi

# check if last command failed, clearup and exit if it has.
function hasFailed {
    echo "Failed to build, reason: $2"
    echo "Clearing up build $1"
    buildah rm $1
    exit 1
}

# Log in to dockerhub
buildah login --get-login docker.io || {
    buildah login docker.io || {
	echo "Failed to login"
	exit 1
    }
}

# Pull the caddy server container to use as a base for the final deployment.
finalbuild=$(buildah from docker.io/library/caddy:2-alpine)

# Be warned, some of the buildah commands do not handle Bash interpretation so if you put variables
# in them it will use the string value of the variable symbol rather than its interpretation, so
# for these the values have to be hard coded.

buildah run ${finalbuild} -- ash -c 'apk update && apk upgrade' || {
    hasFailed ${finalbuild} "Inital command failed"
}

buildah config --workingdir '/usr/share/caddy' ${finalbuild} || {
    hasFailed ${finalbuild} "Could not set workdir"
}

{
    # Copy the contents of the dist directory over to caddy's root directory.
    buildah copy ${finalbuild} 'docs/' '/usr/share/caddy/'

    # Copy the specified artifact to the container.
    buildah copy ${finalbuild} 'Caddyfile' '/etc/caddy/Caddyfile'
} || {
    hasFailed ${finalbuild} "Could not copy files to container"
}

# Commit the final image.
buildah commit ${finalbuild} ${NAME} || {
    hasFailed ${finalbuild} "Could not commit working container"
}

# Clean up the old containers.
buildah rm ${finalbuild}


# If there is a VCS tag then we want to update the container tag with that, otherwise use the VCS commit hash.
if [ "$TAG" = "tag" ]
then
    builah tag ${NAME} "${NAME}:$VERSION"
else
    buildah tag ${NAME} "${NAME}:$COMMIT"
fi || {
    echo "Could not set version or commit tag"
    exit 1
}

if [ "$TAG" = "tag" ]
then
    buildah push "${NAME}:$VERSION" "docker://docker.io/lavalogic/${NAME}:$VERSION"
else
    buildah push "${NAME}:$COMMIT" "docker://docker.io/lavalogic/${NAME}:$COMMIT"
    buildah push "${NAME}:latest" "docker://docker.io/lavalogic/${NAME}:latest"
fi || {
    echo "Failed to push to repo"
    buildah rmi -f $(buildah images -q ${NAME})
    exit 1
}

buildah rmi -f $(buildah images -q ${NAME})
