#!/usr/bin/bash
#
# console/generate-config.sh — generate udev rules + ser2net.yaml + conman.conf
#
# Reads console/mapping.txt (the source of truth) and generates all three
# config files. This is the fix for the USB enumeration shift problem:
#
#   1. udev rules pin each adapter by its STABLE ID_PATH (physical USB port)
#      to a named symlink like /dev/consoles/pfv-r5-core-01
#   2. ser2net opens those stable symlinks and exposes them on TCP ports
#      (2001, 2002, ...) bound to the Tailscale IP
#   3. conman connects to those TCP ports for logging + multiplexing
#
# Run this script ON the target host. It writes to:
#   /etc/udev/rules.d/99-console-ports.rules
#   /etc/ser2net.yaml
#   /etc/conman/console-consoles.conf  (included by /etc/conman.conf)
#
# Usage:
#   PROX_HOST=pfv-tsys4 bash tests/remote.sh prox-file console/generate-config.sh
#
# Environment overrides:
#   MAPPING_FILE  — path to mapping.txt (default: auto-detect next to this script)
#   TS_IP         — Tailscale IP to bind ser2net on (default: auto-detect)
#   CONMAN_LOGDIR — conman log directory (default: /var/log/conman)
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
MAPPING_FILE="${MAPPING_FILE:-$SCRIPT_DIR/mapping.txt}"
CONMAN_LOGDIR="${CONMAN_LOGDIR:-/var/log/conman}"

UDEV_RULES="/etc/udev/rules.d/99-console-ports.rules"
SER2NET_CONF="/etc/ser2net.yaml"
CONMAN_CONF="/etc/conman.conf"

echo "============================================"
echo "  Console Config Generator"
echo "  Host: $(hostname)   $(date)"
echo "============================================"

# --- Locate mapping file ---
# When run via remote.sh prox-file, $0 is bash and $SCRIPT_DIR may be wrong.
# Search common locations.
if [ ! -f "$MAPPING_FILE" ]; then
  for candidate in \
    "/root/console/mapping.txt" \
    "/tmp/mapping.txt" \
    "$(dirname "$0")/mapping.txt"; do
    if [ -f "$candidate" ]; then
      MAPPING_FILE="$candidate"
      break
    fi
  done
fi

if [ ! -f "$MAPPING_FILE" ]; then
  echo "FATAL: mapping file not found. Tried: $MAPPING_FILE"
  echo "Copy mapping.txt to the target host first."
  exit 1
fi
echo "  Mapping file: $MAPPING_FILE"

# --- Auto-detect Tailscale IP ---
if [ -z "${TS_IP:-}" ]; then
  TS_IP=$(tailscale ip -4 2>/dev/null || true)
  if [ -z "$TS_IP" ]; then
    echo "FATAL: could not auto-detect Tailscale IP. Set TS_IP manually."
    exit 1
  fi
fi
echo "  Tailscale IP: $TS_IP"
echo "  ser2net will bind to: $TS_IP"

# --- Parse mapping file (skip comments and blank lines) ---
echo ""
echo "--- Parsing mapping file ---"
ENTRIES=()
while IFS= read -r line; do
  # Skip comments and blank lines
  line="${line%%#*}"
  line="$(echo "$line" | xargs)"  # trim whitespace
  [ -z "$line" ] && continue
  ENTRIES+=("$line")
  echo "  $line"
done < "$MAPPING_FILE"

if [ "${#ENTRIES[@]}" -eq 0 ]; then
  echo "FATAL: no entries found in mapping file."
  exit 1
fi

echo ""
echo "  ${#ENTRIES[@]} console ports configured."

# ============================================================
# 1. Generate udev rules
# ============================================================
echo ""
echo "--- [1/3] Generating udev rules: $UDEV_RULES ---"

cat > "$UDEV_RULES" <<'UDEV_HEADER'
# Stable symlinks for USB-DB9 console adapters
# Generated by console/generate-config.sh
# DO NOT EDIT — edit mapping.txt and re-run generate-config.sh
#
# These rules pin each adapter to a named symlink based on its physical
# USB port path (ID_PATH), which is stable across reboots regardless of
# enumeration order. This is the fix for the "USB adapters shift on reboot"
# problem.
#
# To find the ID_PATH for a device:
#   udevadm info -q all -n /dev/ttyUSBN | grep ID_PATH
UDEV_HEADER

for entry in "${ENTRIES[@]}"; do
  IFS='|' read -r tcp_port name id_path baud comment <<< "$entry"
  # Build the full ID_PATH match. The mapping stores a substring like "usb-0:1.5.4.4"
  # The actual ID_PATH is like "pci-0000:00:1a.0-usb-0:1.5.4.4:1.0"
  # We match on the substring to be portable across PCI bus changes.
  {
    echo ""
    echo "# $name (TCP $tcp_port): $comment"
    echo "SUBSYSTEM==\"tty\", ENV{ID_PATH}==\"*$id_path*\", SYMLINK+=\"consoles/$name\""
  } >> "$UDEV_RULES"
done

echo "  Written: $UDEV_RULES"
echo "  Symlinks: /dev/consoles/<name> for each device"

# ============================================================
# 2. Generate ser2net.yaml
# ============================================================
echo ""
echo "--- [2/3] Generating ser2net config: $SER2NET_CONF ---"

# Backup existing config if not already backed up
if [ -f "$SER2NET_CONF" ] && [ ! -f "${SER2NET_CONF}.orig" ]; then
  cp "$SER2NET_CONF" "${SER2NET_CONF}.orig"
  echo "  Backed up original to ${SER2NET_CONF}.orig"
fi

{
  echo "%YAML 1.1"
  echo "---"
  echo "# ser2net configuration for pfv-tsys4 console ports"
  echo "# Generated by console/generate-config.sh on $(date)"
  echo "#"
  echo "# All ports use telnet(rfc2217) accepter so conman and telnet clients"
  echo "# negotiate proper telnet binary mode — this prevents CR stripping"
  printf '%s\n' "# and stair-stepping on devices that send \\n\\r (LF+CR) line endings."
  echo "# Ports bound to Tailscale IP ($TS_IP) for secure remote access."
  echo "#"
  echo "# Direct telnet:  telnet $TS_IP 2001"
  echo "# Via conman:     conman -f <name>"
  echo ""
  printf '%s\n' "define: &banner \\r\\nPFV console port \\p device \\d [\\B]\\r\\n\\r\\n"
  echo ""

  for entry in "${ENTRIES[@]}"; do
    IFS='|' read -r tcp_port name id_path baud comment <<< "$entry"
    # ser2net connection block — telnet(rfc2217) accepter so conman and
    # telnet clients negotiate proper telnet binary mode. This prevents
    # CR stripping that occurs with raw TCP + conman's telnet NVT.
    echo "connection: &con${tcp_port}"
    echo "    accepter: telnet(rfc2217),tcp,${TS_IP},${tcp_port}"
    echo "    enable: on"
    echo "    options:"
    echo "      banner: *banner"
    echo "      kickolduser: true"
    echo "      telnet-brk-on-sync: true"
    echo "    connector: serialdev,"
    echo "              /dev/consoles/${name},"
    echo "              ${baud},local"
    echo ""
  done
} > "$SER2NET_CONF"

echo "  Written: $SER2NET_CONF"
echo "  ${#ENTRIES[@]} TCP ports configured ($TS_IP:2001-20XX)"

# ============================================================
# 3. Write conman console entries directly into conman.conf
# ============================================================
# conman 0.3.x does NOT support the 'include' directive, so we write
# CONSOLE entries directly into /etc/conman.conf between idempotent markers.
echo ""
echo "--- [3/3] Writing conman consoles into $CONMAN_CONF ---"

# Ensure logdir exists
mkdir -p "$CONMAN_LOGDIR" 2>/dev/null || true

# Ensure LOGDIR is set in conman.conf (server-level directive for log file paths)
if ! grep -qiE '^\s*server\s+logdir\s*=' "$CONMAN_CONF" 2>/dev/null; then
  # Insert near the top, after the first SERVER directives
  sed -i "1i\\server logdir = \"$CONMAN_LOGDIR\"" "$CONMAN_CONF"
  echo "  Added server logdir = \"$CONMAN_LOGDIR\" to $CONMAN_CONF"
fi

# Ensure loopback=off so conmand is reachable over Tailscale (not localhost-only)
if ! grep -qiE '^\s*server\s+loopback\s*=' "$CONMAN_CONF" 2>/dev/null; then
  sed -i "/^server logdir/a server loopback=off" "$CONMAN_CONF"
  echo "  Added server loopback=off to $CONMAN_CONF (enables remote access)"
fi

# Remove any previous auto-generated block (between markers)
# Then append the new block
MARKER_BEGIN="# BEGIN PFV CONSOLE DEFINITIONS (auto-generated — do not edit between markers)"
MARKER_END="# END PFV CONSOLE DEFINITIONS"

# Strip old block if present
if grep -q "$MARKER_BEGIN" "$CONMAN_CONF" 2>/dev/null; then
  sed -i "/$MARKER_BEGIN/,/$MARKER_END/d" "$CONMAN_CONF"
  echo "  Removed previous console definitions."
fi

# Append new block
{
  echo ""
  echo "$MARKER_BEGIN"
  echo "# Generated by console/generate-config.sh on $(date)"
  echo "# Each console connects to a ser2net TCP port via telnet protocol."
  echo "# ser2net uses telnet(rfc2217) accepter so binary mode is negotiated"
  echo "# and CR/LF translation is handled correctly by the telnet NVT layer."
  echo "# Access: conman -f <name>"
  echo ""
  for entry in "${ENTRIES[@]}"; do
    IFS='|' read -r tcp_port name id_path baud comment <<< "$entry"
    echo "CONSOLE name=\"${name}\" dev=\"${TS_IP}:${tcp_port}\" log=\"${name}.log\" logopts=\"timestamp\""
  done
  echo "$MARKER_END"
} >> "$CONMAN_CONF"

CONSOLE_COUNT=$(grep -c "^CONSOLE " "$CONMAN_CONF" 2>/dev/null || echo 0)
echo "  Written $CONSOLE_COUNT CONSOLE entries to $CONMAN_CONF"

# ============================================================
# Summary
# ============================================================
echo ""
echo "============================================"
echo "  Configuration generated successfully."
echo ""
echo "  Files written:"
echo "    $UDEV_RULES       ($(wc -l < "$UDEV_RULES") lines)"
echo "    $SER2NET_CONF     ($(wc -l < "$SER2NET_CONF") lines)"
echo "    $CONMAN_CONF      (CONSOLE entries appended between markers)"
echo ""
echo "  Next steps:"
echo "    1. Reload udev:   udevadm control --reload-rules && udevadm trigger"
echo "    2. Restart ser2net: systemctl restart ser2net"
echo "    3. Start conman:  systemctl enable --now conmand"
echo "    4. Or run:       bash $(basename "$0" .sh | sed 's/generate-config/setup/') .sh"
echo "============================================"
