#!/bin/sh
# script/publish: build the image on the Docker host and push it to the
# registry under four tags: the UTC date (YYYY-MM-DD), the short commit
# hash, the branch name and latest. The build is script/docker's, so the
# tests and the linter run first. The host and the registry name are
# environment variables with defaults, for running it against another.
#
# The working tree must be clean: the hash tag names a commit, and an
# image built from uncommitted changes would carry a hash that does not
# describe it.
set -eu

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"

: "${DOCKER_HOST:=ssh://root@fsn1app1}"
: "${PUBLISH_IMAGE:=git.eeqj.de/sneak/smallwebwaf}"
export DOCKER_HOST

main() {
    cd "$ROOT"

    if [ -n "$(git status --porcelain)" ]; then
        echo "script/publish: the working tree is not clean; commit or stash first" >&2
        exit 1
    fi

    date="$(date -u +%Y-%m-%d)"
    hash="$(git rev-parse --short HEAD)"
    branch="$(git rev-parse --abbrev-ref HEAD)"
    if [ "$branch" = "HEAD" ]; then
        echo "script/publish: detached HEAD; check out a branch first" >&2
        exit 1
    fi
    # A tag is [A-Za-z0-9_.-]; a branch name such as feature/x is not.
    branch="$(printf '%s' "$branch" | tr -c 'A-Za-z0-9_.-' '-')"

    local_tag="$("$SCRIPT_DIR/projectname")"
    "$SCRIPT_DIR/docker"

    for tag in "$date" "$hash" "$branch" latest; do
        docker tag "$local_tag" "$PUBLISH_IMAGE:$tag"
    done
    for tag in "$date" "$hash" "$branch" latest; do
        docker push "$PUBLISH_IMAGE:$tag"
    done

    echo "pushed $PUBLISH_IMAGE with tags: $date $hash $branch latest"
}

main "$@"
