#!/bin/bash
# ==========================================================
#  CyberTools Admin – Restore Manager
# ==========================================================
#  Version : 1.7.5
#  Author  : Jeffery Joe Raskin
#  Release : 2025-10-17
# ==========================================================

set -u

# ────────── Base Paths & Config ──────────
BASE_DIR="/root/cybertoolsadmin"
CONFIG="${BASE_DIR}/config.conf"
[ -f "$CONFIG" ] && source "$CONFIG"

VERSION="1.7.5"
AUTHOR="Jeffery Joe Raskin"
RELEASE_DATE="2025-10-17"

BACKUPDIR="${BACKUPDIR:-/home/backup}"
PROJECTDIR="${PROJECTDIR:-/home/sealproven.com/public_html/sealproven-saas-pilot}"
TEMP_RESTORE="/home/restore-test/project"
RESTORE_LOG="/var/log/cybertools-restore.log"

mkdir -p "$TEMP_RESTORE"
mkdir -p "$(dirname "$RESTORE_LOG")"

# ────────── Colors ──────────
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
CYAN='\033[1;36m'
BOLD='\033[1m'
RESET='\033[0m'

pause() { read -rp "Press Enter to return..."; }

# ────────── Execution Identity ──────────
SCRIPT_PATH="$0"
command -v readlink >/dev/null 2>&1 && SCRIPT_PATH="$(readlink -f "$0" 2>/dev/null || echo "$0")"

MODE="PROD"
[ "${DEV_MODE:-0}" = "1" ] || [[ "$SCRIPT_PATH" == */src/* ]] && MODE="DEV"

EXEC_TYPE="SCRIPT"
[[ "$SCRIPT_PATH" != *.sh ]] && EXEC_TYPE="COMPILED"

# ────────── Logging ──────────
record_restore_log() {
  echo "$(date '+%Y-%m-%d %H:%M:%S') | $1" >> "$RESTORE_LOG"
}

# ────────── Restore Mode Badges ──────────
render_restore_badge() {
  case "$1" in
    simulate) echo -e "${CYAN}🟦 SIMULATION MODE — READ ONLY${RESET}\n" ;;
    safe)     echo -e "${GREEN}🟩 SAFE MODE — TEMP DIRECTORY${RESET}\n" ;;
    direct)   echo -e "${RED}🟥 DIRECT MODE — LIVE OVERWRITE${RESET}\n" ;;
  esac
}

# ────────── Notes ──────────
render_restore_notes() {
  echo -e "${CYAN}=== Notes ===${RESET}"
  echo "• System Restore works only with CyberToolsAdmin system-backup-*.tar.gz files"
  echo "• CyberPanel backups are directory-based and restored via CyberPanel"
  echo "• If System Restore shows no backups, run Admin Backup → System Backup"
  echo
}

# ────────── Backup Discovery ──────────
list_project_backups() {
  find "$BACKUPDIR" -maxdepth 1 -type f -iname "*backup*.tar.gz" \
    -printf "%T@ %p\n" 2>/dev/null | sort -nr | awk '{print $2}'
}

list_system_backups() {
  find "$BACKUPDIR" -maxdepth 1 -type f -iname "system-backup-*.tar.gz" \
    -printf "%T@ %p\n" 2>/dev/null | sort -nr | awk '{print $2}'
}

list_cyberpanel_backups() {
  find "$BACKUPDIR" -maxdepth 1 -type d \
    -regex ".*/[0-9]\{2\}\.[0-9]\{2\}\.[0-9]\{4\}_[0-9-]\+" \
    | sort -r
}

choose_backup_file() {
  local files=("$@")
  local total="${#files[@]}"
  SELECTED_FILE=""

  if [ "$total" -eq 0 ]; then
    echo -e "${YELLOW}No CyberToolsAdmin system backups found.${RESET}"
    echo
    echo "Expected format:"
    echo "  system-backup-YYYYMMDD_HHMMSS.tar.gz"
    echo
    echo "CyberPanel backups were detected under:"
    echo "  /home/backup/YYYY.MM.DD_*"
    echo
    echo "Use:"
    echo "  CyberPanel Restore (guided)"
    return 1
  fi

  echo
  for i in "${!files[@]}"; do
    printf "  %2d) %s\n" "$((i+1))" "$(basename "${files[$i]}")"
  done
  echo
  read -rp "Choose a number (or X to cancel): " choice

  [[ "$choice" =~ ^[xX]$ ]] && return 1
  [[ "$choice" =~ ^[0-9]+$ ]] || return 1
  [ "$choice" -lt 1 ] || [ "$choice" -gt "$total" ] && return 1

  SELECTED_FILE="${files[$((choice-1))]}"
  return 0
}

# ────────── Restore Operations ──────────
simulate_restore() {
  render_restore_badge simulate
  tar -tzf "$1" | head -n 40
  record_restore_log "[SIMULATE] $1"
}

safe_restore() {
  render_restore_badge safe
  rm -rf "$TEMP_RESTORE"
  mkdir -p "$TEMP_RESTORE"
  pv "$1" | tar -xz -C "$TEMP_RESTORE"
  record_restore_log "[SAFE] $1 → $TEMP_RESTORE"
}

direct_restore() {
  render_restore_badge direct
  echo -e "${RED}THIS ACTION IS IRREVERSIBLE.${RESET}"
  echo -e "${RED}Type: DIRECT-RESTORE to continue${RESET}"
  read -rp "> " confirm
  [[ "$confirm" != "DIRECT-RESTORE" ]] && return
  pv "$1" | tar -xz -C "$PROJECTDIR"
  record_restore_log "[DIRECT] $1 → $PROJECTDIR"
}

# ────────── CyberPanel Restore (Guided) ──────────
cyberpanel_restore_help() {
  clear
  echo -e "${BOLD}=== CyberPanel Restore (Guided) ===${RESET}"
  echo
  echo "CyberPanel backups were detected."
  echo "These backups were created when CyberToolsAdmin"
  echo "invoked CyberPanel's native backup engine."
  echo
  echo "Backup directories:"
  echo

  mapfile -t cp_dirs < <(list_cyberpanel_backups)

  if [ "${#cp_dirs[@]}" -eq 0 ]; then
    echo -e "${YELLOW}No CyberPanel backup directories found.${RESET}"
  else
    for d in "${cp_dirs[@]}"; do
      echo " • $(basename "$d")"
    done
  fi

  echo
  echo -e "${CYAN}Restore Methods:${RESET}"
  echo
  echo "Option A — CyberPanel UI (Recommended)"
  echo "  1) Log into CyberPanel"
  echo "  2) Backup → Restore Backup"
  echo "  3) Select date and domain"
  echo
  echo "Option B — CyberPanel CLI (Advanced)"
  echo "  /usr/local/CyberCP/plogical/backupUtilities.py restore"
  echo
  echo "Note:"
  echo "CyberPanel owns restore for these backups."
  echo

  record_restore_log "[INFO] CyberPanel restore guidance viewed"
  pause
}

# ────────── Main Menu ──────────
restore_menu() {
  local LOOP=0

  while true; do
    LOOP=$((LOOP + 1))
    clear

    echo -e "${BOLD}=== CyberTools Admin Restore – v${VERSION} ===${RESET}"
    echo "Author: $AUTHOR    Release: $RELEASE_DATE"
    echo "Mode: $MODE | Type: $EXEC_TYPE"
    echo "Script: $SCRIPT_PATH"
    echo "Menu Loop: $LOOP"
    echo
    echo "1) 📦 Project Restore  (simulate / safe / direct)"
    echo "2) 🧩 System Restore   (CyberToolsAdmin archives)"
    echo "3) 🧱 CyberPanel Restore (guided / manual)"
    echo "4) 🗃️  View Restore Logs"
    echo
    echo "X) Exit to Backup Menu"
    echo

    render_restore_notes

    read -rp "Choose an option: " opt
    case "$opt" in
      1)
        mapfile -t files < <(list_project_backups)
        choose_backup_file "${files[@]}" || { pause; continue; }
        f="$SELECTED_FILE"
        read -rp "Simulate (S), Safe (A), Direct (D): " m
        case "${m,,}" in
          s) simulate_restore "$f" ;;
          a) safe_restore "$f" ;;
          d) direct_restore "$f" ;;
        esac
        pause
        ;;
      2)
        mapfile -t files < <(list_system_backups)
        choose_backup_file "${files[@]}" || { pause; continue; }
        f="$SELECTED_FILE"
        read -rp "Simulate (S), Safe (A), Direct (D): " m
        case "${m,,}" in
          s) simulate_restore "$f" ;;
          a) safe_restore "$f" ;;
          d) direct_restore "$f" ;;
        esac
        pause
        ;;
      3) cyberpanel_restore_help ;;
      4)
        clear
        cat "$RESTORE_LOG" 2>/dev/null || echo "No restore logs yet."
        pause
        ;;
      [xX]) exit 0 ;;
    esac
  done
}

restore_menu
