#!/bin/bash
# LexiVirt OS recovery menu (boot entry "LexiVirt OS recovery").
# Runs on the local console only; no network service is started in this mode.
set -u
MAC=$(cat /etc/lexivirt/mgmt-mac 2>/dev/null || true)
while true; do
  clear
  echo "LexiVirt OS recovery — $(cat /etc/lexivirt-release 2>/dev/null)"
  echo "Management adapter: ${MAC:-unknown}"
  ip -br addr | sed 's/^/  /'
  echo
  echo "  1) Reset the management network to DHCP"
  echo "  2) Reset an administrator password"
  echo "  3) Finish or roll back an interrupted update"
  echo "  4) Roll back the last completed update"
  echo "  5) Show service status and recent errors"
  echo "  6) Shell"
  echo "  7) Continue normal boot"
  read -r -p "Choice: " c
  case "$c" in
    1) [ -z "$MAC" ] && { echo "Management MAC unknown"; read -r _; continue; }
       DEV=$(ip -o link | awk -v m="$MAC" 'tolower($0) ~ tolower(m) {print substr($2,1,length($2)-1); exit}')
       nmcli -t -f NAME,DEVICE con show | awk -F: -v d="$DEV" '$2==d{print $1}' | while read -r n; do nmcli con delete "$n"; done
       nmcli con add type ethernet ifname "$DEV" con-name lexivirt-mgmt ipv4.method auto ipv6.method auto connection.autoconnect yes
       nmcli con up lexivirt-mgmt; read -r -p "Done. Enter to continue" _ ;;
    2) read -r -p "Username: " u; /usr/local/sbin/lexivirtctl reset-password "$u"; read -r -p "Enter to continue" _ ;;
    3) /usr/local/sbin/lexivirt-update --offline recover; read -r -p "Enter to continue" _ ;;
    4) /usr/local/sbin/lexivirt-update --offline rollback; read -r -p "Enter to continue" _ ;;
    5) systemctl --no-pager status lexivirt virtqemud | head -40; journalctl -p err -b --no-pager | tail -20
       /usr/local/sbin/lexivirt-update status | head -40; read -r -p "Enter to continue" _ ;;
    6) bash -l ;;
    7) systemctl isolate multi-user.target; exit 0 ;;
  esac
done
