#!/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. DOCKER_HOST names the Docker host and
# PUBLISH_IMAGE the image in the registry. Both must be set; neither has
# a default.
#
# 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)"

main() {
    if [ -z "${DOCKER_HOST:-}" ]; then
        echo "script/publish: DOCKER_HOST is not set; set it to the Docker host that builds the image, such as ssh://user@build.example.com" >&2
        exit 1
    fi
    if [ -z "${PUBLISH_IMAGE:-}" ]; then
        echo "script/publish: PUBLISH_IMAGE is not set; set it to the image name in the registry, such as registry.example.com/smallwebwaf" >&2
        exit 1
    fi

    cd "$ROOT"

    # Own line: a failing command substitution inside an argument does
    # not trip `set -e`.
    changes="$(git status --porcelain)"
    if [ -n "$changes" ]; 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 "$@"
