#!/bin/bash
set -euo pipefail

source ./common.sh
source ./mac_and_password.sh
source ./ip_management.sh
source ./dns.sh
source ./inventory.sh

usage() {
  cat <<EOF
Usage: $0 --ct-hostname HOSTNAME [OPTIONS]

Options:
  --ct-id ID           Container ID (optional, auto-generated if omitted)
  --ct-hostname NAME   Container hostname (required)
  --ct-desc DESC       Container description (optional)
  --ct-net-id NETID    Network ID (default 10)
  --dry-run            Do not actually create container
  --no-dns             Skip DNS registration
  -h, --help           Show this help message

Example:
  $0 --ct-hostname mycontainer --ct-net-id 20 --dry-run
EOF
}

CT_ID=""
CT_HOSTNAME=""
CT_DESCRIPTION=""
CT_NET_ID="10"
DRY_RUN=false
NO_DNS=false

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

while [[ $# -gt 0 ]]; do
  case $1 in
    --ct-id) CT_ID="$2"; shift 2 ;;
    --ct-hostname) CT_HOSTNAME="$2"; shift 2 ;;
    --ct-desc) CT_DESCRIPTION="$2"; shift 2 ;;
    --ct-net-id) CT_NET_ID="$2"; shift 2 ;;
    --dry-run) DRY_RUN=true; shift ;;
    --no-dns) NO_DNS=true; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown option $1"; usage; exit 1 ;;
  esac
done

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

create_lxc_container() {
  MAC_ADDRESS=$(generate_mac)
  CT_NET_ID="$CT_NET_ID"
  if ! CT_IP=$(./ip_management.sh --ct-net-id "$CT_NET_ID" --mac-address "$MAC_ADDRESS" | grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}'); then
    echo "❌ Failed to find free IP"
    exit 1
  fi

  # Extract last octet of IP as CT_IP number
  CT_IP="${CT_IP##*.}"

  if [[ -z "$CT_ID" ]]; then
    if (( CT_IP < 100 )); then
      CT_ID="100$CT_IP"
    else
      CT_ID="10$CT_IP"
    fi
  fi

  CT_ROOT_PASS=$(generate_root_password)
  echo "$CT_ROOT_PASS" > "$LOG_DIR/ct-${CT_ID}-rootpass.txt"
  echo "🔐 Password saved to $LOG_DIR/ct-${CT_ID}-rootpass.txt"

  echo "🚀 Creating container VMID=$CT_ID, IP=192.168.$CT_NET_ID.$CT_IP"

  if [[ "$DRY_RUN" == true ]]; then
    echo "🧪 Dry-run mode enabled. Skipping actual creation."
  else
    pct create "$CT_ID" \
      /mnt/pve/nas-software/template/cache/debian-12-standard_12.7-1_amd64.tar.zst \
      --hostname "$CT_HOSTNAME" \
      --description "$CT_DESCRIPTION" \
      --cores 2 --memory 4096 --swap 1024 \
      --net0 name=eth0,bridge=vmbr0,firewall=0,gw=192.168."$CT_NET_ID".1,ip=192.168."$CT_NET_ID"."$CT_IP"/24,hwaddr="$MAC_ADDRESS",type=veth \
      --rootfs 8 --storage tier1 --unprivileged 1 --ostype debian --password="$CT_ROOT_PASS" \
      --onboot 1 --nameserver 192.168.10.4 --searchdomain "$DNS_ZONE" \
      --features fuse=1,keyctl=1,nesting=1 \
      --mp5 /lxc_shares/scripts,mp=/opt/scripts_remote \
      --mp6 /lxc_shares/backup,mp=/media/backup --start 0

    echo "lxc.cgroup2.devices.allow: c 10:200 rwm" >> /etc/pve/lxc/${CT_ID}.conf
    echo "lxc.mount.entry: /dev/net/tun dev/net/tun none bind,create=file" >> /etc/pve/lxc/${CT_ID}.conf
  fi

  if [[ "$NO_DNS" != true ]]; then
    ./inventory.sh --export # append_inventory logic can be integrated or called separately
    ./dns.sh --add --hostname "$CT_HOSTNAME" --ip "192.168.$CT_NET_ID.$CT_IP"
  fi

  echo "📦 Hostname: $CT_HOSTNAME"
  echo "🌐 IP: 192.168.$CT_NET_ID.$CT_IP"
  echo "🔗 MAC: $MAC_ADDRESS"
  [[ "$NO_DNS" == true ]] && echo "📎 DNS registration skipped"
  [[ "$DRY_RUN" == true ]] && echo "🧪 Dry-run mode: container not created"
}

create_lxc_container
