#!/bin/bash

set -eo pipefail

EXISTING_ROOT=$1
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

user_id=$(id -u)

if [ $user_id -ne 0 ]; then
    echo "Must run as sudo"
    exit 1
fi

function failed()
{
    local error=${1:-Undefined error}
    echo "Failed: $error" >&2
    echo
    echo "USAGE:"
    echo "./update.sh <AUTHSERVE_AGENT_DIRECTORY>"
    echo
    echo "ARGS:"
    echo "    <AUTHSERVE_AGENT_DIRECTORY>: the directory where the agent was initially installed."
    exit 1
}

if [[ -d $EXISTING_ROOT ]]; then
    EXISTING_ROOT=$(realpath $EXISTING_ROOT)
    if [[ -f "$EXISTING_ROOT/.service" ]]; then
        SERVICE_NAME=$(cat "$EXISTING_ROOT/.service")
    else
        failed "Please pass in the directory where the agent was initially installed."
    fi
    if [[ ! -d "$EXISTING_ROOT/bin" ]]; then
        failed "Current agent directory must contain a 'bin' directory"
    fi
else
    failed "Please pass in the directory where the agent was initially installed."
fi

if [[ ! -d "${SCRIPT_DIR}/bin" ]]; then
    failed "Update package must contain a 'bin' directory"
fi

echo "Stopping ${SERVICE_NAME} during upgrade"
systemctl stop "${SERVICE_NAME}"

EXISTING_BIN_DIR="$EXISTING_ROOT/bin"
EXISTING_BIN_DIR_USER=$(stat -c '%u' $EXISTING_BIN_DIR)
EXISTING_BIN_DIR_GROUP=$(stat -c '%g' $EXISTING_BIN_DIR)

echo "Backing up $EXISTING_BIN_DIR to $EXISTING_BIN_DIR.backup"
rm -rf "$EXISTING_BIN_DIR.backup"
mv -f "$EXISTING_BIN_DIR" "$EXISTING_BIN_DIR.backup"

echo "Copying new agent artifacts"
cp -r "$SCRIPT_DIR/bin" "$EXISTING_ROOT" || "Unable to move new package files to existing agent directory"
chown -R ${EXISTING_BIN_DIR_USER}:${EXISTING_BIN_DIR_GROUP} "$EXISTING_ROOT/bin" || "Failed to restore correct ownership of $EXISTING_ROOT/bin"

echo "Starting ${SERVICE_NAME}"
systemctl start "${SERVICE_NAME}" || "Unable to start ${SERVICE_NAME} after upgrade"

echo "Successfully updated ${SERVICE_NAME}"
