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

install_dir="${HIVE_LINK_INSTALL_DIR:-$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)}"
marker="$install_dir/.update-pending"
boot_count_file="$install_dir/.update-boot-count"
rollback_marker="$install_dir/.update-supervisor-rollback"
max_failed_boots="${HIVE_LINK_MAX_FAILED_UPDATE_BOOTS:-3}"

swap_paths() {
  local current="$1"
  local backup="$2"
  local rejected="${current}.failed-update"
  rm -rf "$rejected"
  mv "$current" "$rejected"
  mv "$backup" "$current"
  mv "$rejected" "$backup"
}

restore_previous_release() {
  if [ -e "$install_dir/workers.backup" ]; then
    swap_paths "$install_dir/workers" "$install_dir/workers.backup"
  elif [ -e "$install_dir/workers.backup.absent" ]; then
    rm -rf "$install_dir/workers"
    rm -f "$install_dir/workers.backup.absent"
  fi

  if [ -e "$install_dir/version.json.backup" ]; then
    swap_paths "$install_dir/version.json" "$install_dir/version.json.backup"
  fi

  swap_paths "$install_dir/hive-link" "$install_dir/hive-link.backup"
  printf '%s\n' 'crash_loop' > "${rollback_marker}.new"
  mv "${rollback_marker}.new" "$rollback_marker"
  sync -f "$rollback_marker" 2>/dev/null || sync
  rm -f "$boot_count_file"
}

if [ -e "$rollback_marker" ]; then
  :
elif [ -e "$marker" ]; then
  boot_count=0
  if [ -r "$boot_count_file" ]; then
    read -r boot_count < "$boot_count_file" || boot_count=0
  fi
  case "$boot_count" in
    ''|*[!0-9]*) boot_count=0 ;;
  esac
  boot_count=$((boot_count + 1))
  count_temp="${boot_count_file}.new"
  printf '%s\n' "$boot_count" > "$count_temp"
  mv "$count_temp" "$boot_count_file"
  sync -f "$boot_count_file" 2>/dev/null || sync

  if [ "$boot_count" -gt "$max_failed_boots" ]; then
    restore_previous_release
  fi
else
  rm -f "$boot_count_file"
fi

exec "$install_dir/hive-link"
