#!/bin/bash
set -euo pipefail
source ./common.sh

usage() {
  cat <<EOF
Usage: $0 --ct-id ID [--ct-net-id NETID] [--force]

Options:
  --ct-id ID        Container ID to delete (required)
  --ct-net-id NETID Network ID (default: 10)
  --force           Force delete without confirmation
  -h, --help        Show this help message

Example:
  $0 --ct-id 10055 --force
EOF
}

CT_ID=""
CT_NET_ID="10"
FORCE_DELETE=false

if [[ $# -eq 0 ]]; then usage; exit 1; fi

while [[ $# -gt 0 ]]; do
  case $1 in
    --ct-id) CT_ID="$2"; shift 2 ;;
    --ct-net-id) CT_NET_ID="$2"; shift 2 ;;
    --force) FORCE_DELETE=true; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown option $1"; usage; exit 1 ;;
  esac
done

if [[ -z "$CT_ID" ]]; then
  echo "❌ --ct-id is required"
  usage
  exit 1
fi

secure_delete_password() {
  local passfile="$LOG_DIR/ct-${CT_ID}-rootpass.txt"
  if [[ -f "$passfile" ]]; then
    shred -u "$passfile"
    echo "🔐 Password file securely deleted: $passfile"
  fi
}

delete_lxc_container() {
  local status
  status=$(pct status "$CT_ID" 2>/dev/null | awk '{print $2}')
  if [[ "$status" == "running" && "$FORCE_DELETE" != true ]]; then
    read -rp "⚠️ Container $CT_ID is running. Stop it? [y/N]: " confirm
    [[ "$confirm" =~ ^[Yy]$ ]] && pct stop "$CT_ID" || { echo "Aborted."; exit 1; }
  fi

  pct destroy "$CT_ID"
  secure_delete_password

  if [[ -f "$RESERVATION_FILE" ]]; then
    grep -v "192.168.$CT_NET_ID.$CT_IP" "$RESERVATION_FILE" > "$RESERVATION_FILE.tmp"
    mv "$RESERVATION_FILE.tmp" "$RESERVATION_FILE"
    echo "✅ IP 192.168.$CT_NET_ID.$CT_IP released."
  fi

  echo -e "\n🧹 Summary:"
  echo "🔹 VMID deleted : $CT_ID"
  echo "🔹 IP released  : 192.168.$CT_NET_ID.$CT_IP"

  {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Deleted container $CT_ID"
    echo "Released IP: 192.168.$CT_NET_ID.$CT_IP"
  } >> "$LOG_DIR/deletion.log"
}

delete_lxc_container
