#!/usr/bin/env sh

#set -x  # Display the value of PS4, followed by the command and its arguments.
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
REMOTE_URL=${REMOTE_URL:="https://git.dezentrale.cloud/Frontend/Homepage.git"}
CLONE_DIR=${CLONE_DIR="$HOME/homepage"}  # local checkout path

ORIGIN=${ORIGIN="origin"}
BRANCH=${BRANCH="main"}

HUGO_CMD=${HUGO_CMD="hugo"}
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 \
            "$REMOTE_URL" \
            "$CLONE_DIR" \
        || exit 1
    fi
}

# fetch repo updates from remote
fetch_local () {
    if [ -d "$CLONE_DIR" ]; then
        git -C "$CLONE_DIR" fetch \
            --quiet \
            --recurse-submodules \
            --all \
        || exit 1
    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

    fetch_local
    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 remote repo
latest_remote_sha () {
    git -C "$CLONE_DIR" rev-parse --quiet "$ORIGIN/$BRANCH"
}


# do the build
build_page() {
    TMPDIR=$(mktemp -d -t hugo_build_XXXXX)

    $HUGO_CMD \
        --quiet \
        --enableGitInfo \
        --source "$CLONE_DIR" \
        --destination "$TMPDIR" \
    || exit 1

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


# public static void main
if ! setup_local; then
    build_page
    exit 0
fi

if [ $FORCE != "no" ]; then
    build_page
    exit 0
fi

if [ "$(latest_local_sha)" != "$(latest_remote_sha)" ]; then
    purge_local
    clone_local
    build_page
fi

exit 0
