#!/usr/bin/env zsh
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:$HOME/bin
HOSTNAME=$(hostname)
LOCATION=$(hostname|cut -d . -f2)
LOCKFILE="${HOME}/lock"
REF=$(echo "${1:=origin/master}"|sed -e 's!:!/!')

if [ -f "${LOCKFILE}" ];then
    echo "upgrade already running? check lockfile ${LOCKFILE}"
    exit 1
fi

# on exit, remove lockfile but preserve exit code
trap "rv=\$?; rm -f "${LOCKFILE}"; exit \$rv" INT TERM EXIT

# create lockfile
touch "${LOCKFILE}"

# notify logged in users
echo "Upgrading unfurler to ${REF}" | wall

update_repo()
{
    echo "[*] Upgrading unfurler to ${REF}"
    cd "$HOME/unfurl/unfurler" || exit 1

    git fetch origin || exit 1
    for remote in origin;do
        git remote add "${remote}" "https://github.com/${remote}/mempool" >/dev/null 2>&1
        git fetch "${remote}" || exit 1
    done

    if [ $(git tag -l "${REF}") ];then
        git reset --hard "tags/${REF}" || exit 1
    elif [ $(git branch -r -l "origin/${REF}") ];then
        git reset --hard "origin/${REF}" || exit 1
    else
        git reset --hard "${REF}" || exit 1
    fi
    export HASH=$(git rev-parse HEAD)
}

build_backend()
{
    echo "[*] Building backend for unfurler"
    [ -z "${HASH}" ] && exit 1
    cd "$HOME/unfurl/unfurler" || exit 1
    if [ ! -e "config.json" ];then
        cp "${HOME}/unfurl/production/mempool-config.unfurl.json" "config.json"
    fi
    npm install || exit 1
    npm run build || exit 1
}

update_repo
build_backend

# notify everyone
echo "${HOSTNAME} unfurl updated to \`${REF}\` @ \`${HASH}\`" | /usr/local/bin/keybase chat send --nonblock --channel general mempool.dev
echo "${HOSTNAME} unfurl updated to \`${REF}\` @ \`${HASH}\`" | /usr/local/bin/keybase chat send --nonblock --channel general "mempool.ops.${LOCATION}"

exit 0
