#!/bin/bash

set -eu -o pipefail

# shellcheck source=functions.sh.in
source "/usr/libexec/efimirror/functions.sh"

# shellcheck source=/dev/null
source "$EFIMIRROR_CONFIG_PATH"

cmd="${1:-}"
shift || :

usage() {
  echo "Usage: $0 enroll <part-uuid>" >&2
  echo "       $0 unenroll <part-uuid>" >&2
  echo "       $0 status" >&2
  echo "       $0 list-system-partitions" >&2
}

apply_changes() {
  systemctl daemon-reload
  systemctl reset-failed
  systemctl start local-fs.target
}

case "$cmd" in
enroll)
  if [ $# -ne 1 ]; then
    usage
    exit 1
  fi

  partuuid="$1"

  declare -a user_efi_partitions
  get_configured_efi_partitions user_efi_partitions
  if [[ "${user_efi_partitions[*]}" == *"$partuuid"* ]]; then
    echo "Partition already enrolled" >&2
    exit 0
  fi

  declare -a system_efi_partitions
  find_system_efi_partitions system_efi_partitions
  if ! [[ "${system_efi_partitions[*]}" == *"$partuuid"* ]]; then
    echo "Error: partition ${partuuid} not found as a valid EFI partition" >&2
    exit 1
  fi

  echo "$partuuid" >> "$EFIMIRROR_PART_CONFIG_PATH"
  apply_changes
;;
unenroll)
  if [ $# -ne 1 ]; then
    usage
    exit 1
  fi

  partuuid="$1"

  declare -a user_efi_partitions
  get_configured_efi_partitions user_efi_partitions
  if ! [[ "${user_efi_partitions[*]}" == *"$partuuid"* ]]; then
    echo "Partition not enrolled" >&2
    exit 0
  fi

  tmp_config=$(mktemp -p "$(dirname "$EFIMIRROR_PART_CONFIG_PATH")")
  for cur_partuuid in "${user_efi_partitions[@]}"; do
    [ "$cur_partuuid" != "$partuuid" ] || continue
    echo "$cur_partuuid"
  done > "$tmp_config"

  mv "$tmp_config" "$EFIMIRROR_PART_CONFIG_PATH"
  mount_dir="$MOUNT_BASE/${partuuid}"
  systemctl stop "$mount_dir" || :
  apply_changes
;;
status)
  if [ $# -ne 0 ]; then
    usage
    exit 1
  fi

  declare -a efi_partitions
  if ! get_efi_partitions efi_partitions; then
    print "No EFI partitions actively managed"
  else
    echo "* Partition information:"
    # this prints status to stderr
    get_primary_efi_partition efi_partitions > /dev/null
  fi

  mount_unit_prefix=$(systemd-escape --path "$MOUNT_BASE")
  echo "* Unit Status:"
  systemctl status 'efimirror@*' "${mount_unit_prefix}"'-*.mount' --no-pager --lines 0

  exit 0
;;
list-system-partitions)
  if [ $# -ne 0 ]; then
    usage
    exit 1
  fi

  if ! readarray -t system_efi_partitions < <(find_system_efi_partitions | sort -u) || \
    [ "${#system_efi_partitions[@]}" -eq 0 ]
  then
    print "Error: no EFI partitions found, exiting"
    exit 1
  fi

  for partuuid in "${system_efi_partitions[@]}"; do
    canonical_disk=$(realpath "$partuuid" 2>/dev/null || echo "/dev/disk/by-partuuid/$partuuid")
    echo "$canonical_disk"$'\t'"$partuuid"
  done
;;
*)
  usage

  if [ "$cmd" == "--help" ]; then
    exit 0
  else
    exit 1
  fi
esac
