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

usage() {
  cat <<EOF
Usage: $0 [OPTIONS]

Options:
  --ct-net-id NETID     Network ID (default: 10)
  --mac-address MAC     Optional MAC address (auto-generated if omitted)
  --help                Show this help

Description:
  Finds a free IP in the subnet 192.168.NETID.0/24 excluding leased and reserved IPs.
  Prints the free IP and sets global CT_IP and MAC_ADDRESS variables.

EOF
}

CT_NET_ID="10"
MAC_ADDRESS=""

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

if [[ -z "$MAC_ADDRESS" ]]; then
  MAC_ADDRESS=$(generate_mac)
fi

leases=$(ssh "$UDM_SSH_USER@$UDM_HOST" "cat $LEASE_FILE" || true)
used_ips=$(echo "$leases" | awk '{ if ($1 > systime()) print $3 }')
reserved_ips=""
[[ -f "$RESERVATION_FILE" ]] && reserved_ips=$(<"$RESERVATION_FILE")

for i in $(seq 21 253); do
  ip="192.168.$CT_NET_ID.$i"
  if [[ "$used_ips" =~ $ip ]]; then continue; fi
  if [[ "$reserved_ips" =~ $ip ]]; then continue; fi
  if ping -c1 -W1 "$ip" &>/dev/null; then continue; fi

  echo "Free IP found: $ip"
  # Export for caller environment if sourced
  export CT_IP=$i
  export MAC_ADDRESS=$MAC_ADDRESS
  exit 0
done

echo "❌ No free IP found in subnet 192.168.$CT_NET_ID.0/24"
exit 1
