#!/usr/bin/env sh

set -e  # Exit immediately if a command exits with a non-zero status.
set -u  # Treat unset variables as an error when substituting.

FORCE=${FORCE="no"}

# change this to your setup
GIT_BASE=${GIT_BASE="https://git.dezentrale.cloud"}  # no trailing slash please
CLONE_DIR=${CLONE_DIR="$HOME/homepage"}  # local checkout path

OWNER=${OWNER="Frontend"}
REPO=${REPO="Homepage"}
BRANCH=${BRANCH="main"}

GOPATH=${GOPATH="$HOME/go/bin"}
WWWDIR=${WWWDIR="/var/www/www"}

# bugs ahead

# delete repo if it is already there
purge_local () {
    if [ -d "$CLONE_DIR" ]; then
        rm -rf "$CLONE_DIR"
    fi
}

# clone repo if not already there
clone_local () {
    if [ ! -d "$CLONE_DIR" ]; then
        git clone \
            --quiet \
            --branch "$BRANCH" \
            --recurse-submodules \
            "${GIT_BASE}/${OWNER}/${REPO}.git" \
            "$CLONE_DIR"
    fi
}

# make sure repo is cloned, clean and on the correct branch
setup_local () {
    if [ ! -d "$CLONE_DIR" ]; then
        clone_local
        return 1
    fi

    branch=$(git -C "$CLONE_DIR" symbolic-ref --short --quiet HEAD)
    if [ "$branch" != $BRANCH ]; then
        purge_local
        clone_local
        return 1
    fi

    stat=$(git -C "$CLONE_DIR" status --short)
    if [ "$stat" != "" ]; then
        purge_local
        clone_local
        return 1
    fi

    return 0
}


# get latest commit id of cloned repo
latest_local_sha () {
    git -C "$CLONE_DIR" rev-parse --quiet "$BRANCH"
}

# get latest commit id of server
latest_remote_sha () {
    curl -sq \
        -X GET \
        -H "accept: application/json" \
        "${GIT_BASE}/api/v1/repos/${OWNER}/${REPO}/commits?sha=${BRANCH}&limit=1" \
    | jq -M -r '.[0].sha'
}


# determine if build is required
REQUIRED="no"
if ! setup_local; then
    REQUIRED="setup"
elif [ $FORCE != "no" ]; then
    REQUIRED="forced"
elif [ "$(latest_local_sha)" != "$(latest_remote_sha)" ]; then
    REQUIRED="changed"
    purge_local
    clone_local
fi

# do the build
if [ $REQUIRED != "no" ]; then
    TMPDIR=$(mktemp -d -t hugo_build_XXXXX)

    PATH=$PATH:$GOPATH \
        hugo \
            --quiet \
            --enableGitInfo \
            --source "$CLONE_DIR" \
            --destination "$TMPDIR"

    rm -rf "${WWWDIR:?}"/*
    cp -r "$TMPDIR"/. "$WWWDIR"
    rm -rf "$TMPDIR"
fi
