#!/usr/bin/env bash
set -euo pipefail

: "${RELEASE:?RELEASE is required}"
: "${STAMP:?STAMP is required}"

content=/opt/cosmosluminosity/content
parent="$content/themes"
live="$parent/clean"
stage="$parent/.clean-stage-$STAMP"
old="$parent/.clean-before-$STAMP"
settings="$content/settings"
routes="$settings/routes.yaml"
routes_new="$settings/.routes-$STAMP.new"
routes_old="$settings/.routes-$STAMP.before"

assert_spazio_owned() {
  local path=$1
  [[ $(stat -c '%u:%g' "$path") == 1000:1000 ]] || {
    printf 'ownership check failed: %s\n' "$path" >&2
    exit 1
  }
}

[[ $(id -u) -eq 1000 ]] || { echo 'must run as UID 1000 (spazio)' >&2; exit 1; }
[[ -d "$live" && -d "$stage" && ! -e "$old" ]] || { echo 'invalid theme cutover state' >&2; exit 1; }
[[ -f "$routes" && ! -e "$routes_old" ]] || { echo 'invalid routes cutover state' >&2; exit 1; }
assert_spazio_owned "$parent"
assert_spazio_owned "$live"
assert_spazio_owned "$stage"
assert_spazio_owned "$settings"
assert_spazio_owned "$routes"

cd "$RELEASE"
sha256sum -c PAYLOAD_SHA256SUMS >/dev/null
install -m 0644 candidate/routes.yaml "$routes_new"
assert_spazio_owned "$routes_new"
cmp candidate/routes.yaml "$routes_new"

rollback() {
  set +e
  if [[ -d "$old" ]]; then
    [[ -d "$live" ]] && mv "$live" "$stage.failed"
    mv "$old" "$live"
  fi
  if [[ -f "$routes_old" ]]; then
    [[ -f "$routes" ]] && mv "$routes" "$routes_new.failed"
    mv "$routes_old" "$routes"
  fi
}
trap rollback ERR INT TERM

mv "$live" "$old"
mv "$stage" "$live"
mv "$routes" "$routes_old"
mv "$routes_new" "$routes"

assert_spazio_owned "$live"
assert_spazio_owned "$routes"
cmp candidate/routes.yaml "$routes"
trap - ERR INT TERM
printf 'CUTOVER_FILES=PASS\nOLD_THEME=%s\nOLD_ROUTES=%s\n' "$old" "$routes_old"
