#!/bin/bash
# vim: softtabstop=2 shiftwidth=2 expandtab

sources=(
  /lib/profiling-lib.sh
  /etc/zfsbootmenu.conf
  /lib/kmsg-log-lib.sh
  /lib/zfsbootmenu-core.sh
  /lib/zfsbootmenu-ui.sh
  /lib/fzf-defaults.sh
)

for src in "${sources[@]}"; do
  # shellcheck disable=SC1090
  if ! source "${src}" >/dev/null 2>&1 ; then
    echo -e "\033[0;31mWARNING: ${src} was not sourced; unable to proceed\033[0m"
    exit 1
  fi
done

unset src sources

# Replace the global_header function with a stub
global_header() {
  echo -n -e "\\033[1;33m[ Recover from snapshot ]"
}

fs_header() {
  echo -n -e "\\033[1;33m[ Select a filesystem ]"
}

fs="${1}"

if [ -z "${fs}" ]; then
  if ! candidates="$( find_be_candidates 2>/dev/null )"; then
    zerror "no root candidates found; specify a filesystem manually"
    exit 1
  fi

  header="$( column_wrap "^[RETURN] select:[ESCAPE] cancel" )"
  sort_key="$( get_sort_key )"
  preview_label="Sorted by: ${sort_key^}"

  if ! fs="$(
      fzf --header="${header}" --prompt "Filesystem > " \
        ${HAS_BORDER:+--border-label="$( fs_header )"} \
        ${HAS_BORDER:+--preview-label-pos=2:bottom} \
        ${HAS_BORDER:+--preview-label="$( colorize orange " ${preview_label} " )"} \
        --preview-window="up:${PREVIEW_HEIGHT}${HAS_BORDER:+,border-sharp}" \
        --preview="/libexec/zfsbootmenu-preview {} '${BOOTFS}'" <<< "${candidates}"
  )"; then
    tput clear
    exit 0;
  fi
fi

if [ -z "${fs}" ]; then
  zerror "a filesystem must be selected to browse snapshots"
  exit 1
fi

if ! is_zfs_filesystem "${fs}" ; then
  zerror "'${fs}' is not a ZFS filesystem"
  exit 1
fi

COLUMNS="$( tput cols )"

while true; do
  if ! selection="$( draw_snapshots "${fs}" )" ; then
    tput clear
    exit
  fi

  # shellcheck disable=SC2162
  IFS=, read subkey selected_snap <<< "${selection}"
  selected_snap="${selected_snap%,*}"
  
  case "${subkey}" in
    "left"|"right")
      continue
      ;;
  esac

  if is_snapshot "${selected_snap}" ; then
    snapshot_dispatcher "${selected_snap}" "${subkey}"
  fi
done
