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

if [[ ${EUID} -ne 0 ]]; then
  printf '%s\n' "rollback must run as root" >&2
  exit 1
fi
exec 9>/run/lock/harbor-release.lock
if ! flock -n 9; then
	printf '%s\n' "another release or rollback is in progress" >&2
	exit 1
fi
test -f /etc/harbor/previous-release
test -f /etc/harbor/previous-slot

previous_release=$(cat /etc/harbor/previous-release)
previous_slot=$(cat /etc/harbor/previous-slot)
test -d "$previous_release"
if [[ "$previous_slot" == blue ]]; then
  previous_port=8888
else
  previous_port=8889
fi

ln -sfn "$previous_release" "/opt/harbor/slots/$previous_slot"
systemctl start "harbor-gateway@$previous_slot.service"
for _ in $(seq 1 60); do
  curl -fsS "http://127.0.0.1:$previous_port/api/v1/health" >/dev/null && break
  sleep 1
done
curl -fsS "http://127.0.0.1:$previous_port/api/v1/health" >/dev/null
systemctl start "harbor-worker@$previous_slot.service"
sleep 3
systemctl is-active --quiet "harbor-worker@$previous_slot.service"

current_release=$(readlink -f /opt/harbor/current)
current_slot=$(cat /etc/harbor/active-slot)
printf '%s\n' "$current_release" > /etc/harbor/previous-release
printf '%s\n' "$current_slot" > /etc/harbor/previous-slot
ln -sfn "$previous_release" /opt/harbor/current.new
mv -Tf /opt/harbor/current.new /opt/harbor/current
printf 'server 127.0.0.1:%s;\n' "$previous_port" > /etc/nginx/harbor-active-server.conf.new
mv -f /etc/nginx/harbor-active-server.conf.new /etc/nginx/harbor-active-server.conf
nginx -t
systemctl reload nginx
printf '%s\n' "$previous_slot" > /etc/harbor/active-slot
systemctl enable "harbor-gateway@$previous_slot.service" "harbor-worker@$previous_slot.service" >/dev/null
systemctl disable "harbor-gateway@$current_slot.service" "harbor-worker@$current_slot.service" >/dev/null 2>&1 || true
systemctl stop --no-block "harbor-worker@$current_slot.service" 2>/dev/null || true
curl -fsS http://127.0.0.1/health >/dev/null
printf '%s\n' "rolled back to $(basename "$previous_release") on $previous_slot"
