#!/bin/sh
set -eu

SCRIPT_PATH="$0"
case "$SCRIPT_PATH" in
  /*) ;;
  *) SCRIPT_PATH="$(command -v "$0")" ;;
esac
APP_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
STATE_FILE="$APP_DIR/data/deployed-rev"
LOG_FILE="$APP_DIR/data/deploy.log"

mkdir -p "$APP_DIR/data"
cd "$APP_DIR"

remote_output="$(git -c credential.helper="store --file=/var/services/homes/whitekomani/.git-credentials" ls-remote origin refs/heads/main 2>&1 || true)"
remote_rev="$(printf '%s\n' "$remote_output" | awk '/refs\/heads\/main$/ {print $1}')"
if [ -z "$remote_rev" ]; then
  echo "$(date '+%Y-%m-%d %H:%M:%S') no remote revision found: $remote_output" >> "$LOG_FILE"
  exit 1
fi

current_rev=""
[ -f "$STATE_FILE" ] && current_rev="$(cat "$STATE_FILE")"

if [ "$remote_rev" = "$current_rev" ]; then
  exit 0
fi

echo "$(date '+%Y-%m-%d %H:%M:%S') change detected $current_rev -> $remote_rev" >> "$LOG_FILE"
"$APP_DIR/deploy.sh"
printf '%s\n' "$remote_rev" > "$STATE_FILE"
