#!/bin/bash
# netfix-inject.sh — inject permanent static-IP config into the Windows image
# BEFORE first boot. Solves bin456789/reinstall DHCP-provider bug:
#   create_win_set_netconf_script() only writes mac_addr when the source system
#   had a STATIC ip. On a DHCP VPS (Tencent Lighthouse, most cheap tiers) nothing
#   is written, windows-set-netconf.bat hits `if not defined mac_addr goto :del`
#   and exits doing nothing -> Windows boots with no address -> all ports filtered.
#
# Runs from the Alpine installer while the target disk is mounted at /os.
# Usage: bash netfix-inject.sh [IP] [PREFIX] [GATEWAY] [DNS1] [DNS2]
#
# With no args it auto-detects from /dev/netconf (captured pre-wipe by reinstall.sh)
# and falls back to the live Alpine NIC.

set -uo pipefail

OS_DIR=${OS_DIR:-/os}
IP=${1:-}
PREFIX=${2:-}
GW=${3:-}
DNS1=${4:-183.60.83.19}
DNS2=${5:-8.8.8.8}

log() { echo "[netfix] $*"; }
die() { echo "[netfix] FATAL: $*" >&2; exit 1; }

# CRLF conversion that is IDEMPOTENT. The naive `sed 's/$/\r/'` fallback appends
# a second CR to a file that is already CRLF, producing `\r\r\n`. cmd.exe then
# mis-parses the .bat and the netfix never runs. Always normalise first.
tocrlf() {
    local f=$1
    [ -f "$f" ] || return 0
    if command -v unix2dos >/dev/null 2>&1; then
        unix2dos -q "$f" 2>/dev/null && return 0
    fi
    local tmp="$f.crlf.$$"
    sed 's/\r$//' "$f" | sed 's/$/\r/' > "$tmp" && mv "$tmp" "$f"
    chmod 644 "$f" 2>/dev/null || true
    return 0
}

[ -d "$OS_DIR/Windows" ] || die "$OS_DIR/Windows not found — is the disk mounted at /os?"

# MAC of the source NIC, used by the PowerShell side to pick the right adapter
# when Windows renames it (VirtIO NICs are frequently "Ethernet 2" or "Ethernet 3").
MAC=${MAC:-}

# ---------------------------------------------------------------- autodetect
if [ -z "$IP" ]; then
    # /dev/netconf/<iface>/ holds what reinstall.sh captured from the live system
    for d in /dev/netconf/*/; do
        [ -f "$d/ipv4_addr" ] || continue
        a=$(cat "$d/ipv4_addr" 2>/dev/null)
        g=$(cat "$d/ipv4_gateway" 2>/dev/null)
        [ -n "$a" ] && [ -n "$g" ] || continue
        IP=${a%%/*}; PREFIX=${a##*/}; GW=$g
        [ -n "$MAC" ] || MAC=$(cat "$d/mac_addr" 2>/dev/null)
        log "detected from $d : $IP/$PREFIX gw=$GW mac=${MAC:-none}"
        break
    done
fi

# fall back to the live Alpine interface
if [ -z "$IP" ]; then
    for i in eth0 eth1 ens3 ens4; do
        a=$(ip -4 -o addr show dev "$i" 2>/dev/null | awk '{print $4}' | head -1)
        g=$(ip route 2>/dev/null | awk '/^default/{print $3; exit}')
        if [ -n "$a" ] && [ -n "$g" ]; then
            IP=${a%%/*}; PREFIX=${a##*/}; GW=$g
            [ -n "$MAC" ] || MAC=$(cat "/sys/class/net/$i/address" 2>/dev/null || echo "")
            log "detected from live $i : $IP/$PREFIX gw=$GW mac=${MAC:-none}"
            break
        fi
    done
fi

# last resort: the recorded preflight capture (survives a wiped /dev)
if { [ -z "$IP" ] || [ -z "$GW" ]; } && [ -f /net-backup/network.txt ] 2>/dev/null; then
    . /net-backup/network.txt 2>/dev/null || true
fi

[ -n "$IP" ] && [ -n "$GW" ] || die "could not determine IP/gateway — pass them as args"

# ---- NAT guard ---------------------------------------------------------------
# If preflight determined the host is behind edge NAT, the guest must keep the
# PRIVATE address. Injecting the public IP onto the NIC gives the guest an
# address it does not own, and the box goes completely dark (this is exactly
# the class of failure this whole tool exists to prevent).
is_private() {
    case "$1" in
        10.*|192.168.*|172.1[6-9].*|172.2[0-9].*|172.3[0-1].*) return 0 ;;
        *) return 1 ;;
    esac
}
if [ "${NAT:-0}" = 1 ]; then
    if ! is_private "$IP"; then
        die "host is NAT (edge public IP) but IP=$IP is public — this would break the return path. Pass the NIC's private address instead."
    fi
    log "NAT host confirmed: using private $IP on the NIC (edge maps the public IP)"
elif is_private "$IP"; then
    # No NAT flag but a private address: still correct for a private-only box.
    log "private address $IP — assuming edge NAT"
fi

# WINDOWS_IP wins when preflight recorded it: it is the address Windows must use.
if [ -n "${WINDOWS_IP:-}" ] && [ "$WINDOWS_IP" != "$IP" ]; then
    log "using WINDOWS_IP=$WINDOWS_IP (recorded by preflight) instead of $IP"
    IP="$WINDOWS_IP"
fi

# DNS from the live resolver, skipping systemd-resolved loopback stubs
if [ -z "${DNS1_SET:-}" ]; then
    live=$(awk '/^nameserver/{print $2}' /etc/resolv.conf 2>/dev/null | grep -vE '^(127\.|::1)' | head -2 | tr '\n' ' ')
    if [ -n "$live" ]; then
        set -- $live
        DNS1=${1:-$DNS1}; DNS2=${2:-$DNS2}
    fi
fi

# prefix -> dotted netmask (full /0../32 range; the old helper only did /8../28)
prefix_to_mask() {
    p=$1
    [ "$p" -ge 0 ] 2>/dev/null && [ "$p" -le 32 ] 2>/dev/null || { echo "255.255.255.0"; return; }
    local mask="" filled=$((p / 8)) rest=$((p % 8)) i=0 octet
    while [ $i -lt 4 ]; do
        if [ $i -lt $filled ]; then octet=255
        elif [ $i -eq $filled ]; then octet=$(( (256 - (1 << (8 - rest))) % 256 ))
        else octet=0; fi
        mask="$mask${mask:+.}$octet"
        i=$((i + 1))
    done
    echo "$mask"
}

MASK=$(prefix_to_mask "$PREFIX")
[ "$GW" != "${GW#*:*}" ] && die "IPv6 gateway unsupported by this injector"

# gateway must sit inside the subnet, else Windows silently rejects the config.
# NOTE: pure-bash on purpose — python3 is NOT present in the Alpine installer
# image, and hard-depending on it made stage 2 die on a minimal netboot.
ip_to_int() {
    local IFS=. o
    for o in $1; do printf '%02x' "$o"; done
}
validate_gateway() {
    local _ip=$1 _pfx=$2 _gw=$3 _ipn _gwn _net _mask
    case "$_ip" in *[!0-9.]*|"") return 1 ;; esac
    case "$_gw" in *[!0-9.]*|"") return 1 ;; esac
    case "$_pfx" in *[!0-9]*|"") return 1 ;; esac
    [ "$_pfx" -le 32 ] || return 1
    _ipn=$((0x$(ip_to_int "$_ip")))
    _gwn=$((0x$(ip_to_int "$_gw")))
    # /0 would shift by 32 which is UB in bash; treat separately
    if [ "$_pfx" -eq 0 ]; then _mask=$((0)); else _mask=$(( (0xFFFFFFFF << (32 - _pfx)) & 0xFFFFFFFF )); fi
    _net=$(( _ipn & _mask ))
    [ $(( _gwn & _mask )) -eq "$_net" ]
}
validate_gateway "$IP" "$PREFIX" "$GW" || die "gateway $GW not inside $IP/$PREFIX (Windows would reject this config silently)"

log "config: ip=$IP mask=$MASK prefix=/$PREFIX gw=$GW dns=$DNS1,$DNS2"

# ------------------------------------------------------------- write config
# One file per detected iface, plus a generic name, so it still runs if the
# Windows NIC ends up named differently after driver load.
ENVFILE="windows-netfix-config.bat"
cat > "$OS_DIR/$ENVFILE" <<EOF
@echo off
rem --- netfix static config (generated $(date -u +%Y-%m-%dT%H:%M:%SZ)) ---
set NETFIX_IP=$IP
set NETFIX_MASK=$MASK
set NETFIX_GW=$GW
set NETFIX_DNS1=$DNS1
set NETFIX_DNS2=$DNS2
set NETFIX_MAC=$MAC
EOF
tocrlf "$OS_DIR/$ENVFILE"

# PowerShell does the work: Get-NetAdapter + ifIndex, so it does not depend on
# the interface being named "Ethernet" (VirtIO NICs often come up as Ethernet 2/3).
PS1="windows-netfix.ps1"
cat > "$OS_DIR/$PS1" <<'EOF'
$ErrorActionPreference = 'Continue'
$log = "$env:SystemDrive\netfix-result.txt"
function W($m) { "$([DateTime]::Now.ToString('HH:mm:ss')) $m" | Tee-Object -FilePath $log -Append }

W "=== netfix start ==="

# read the generated config directly — `set VAR=` inside a .bat is NOT an
# environment variable for a separate PowerShell process, so env lookup alone
# would silently produce an empty config.
$cfgPath = "$env:SystemDrive\windows-netfix-config.bat"
$ip=''; $mask=''; $gw=''; $d1=''; $d2=''; $netfixMac=''
if (Test-Path $cfgPath) {
    foreach ($line in Get-Content $cfgPath) {
        if ($line -match 'NETFIX_IP=(\S+)')   { $ip   = $Matches[1] }
        if ($line -match 'NETFIX_MASK=(\S+)') { $mask = $Matches[1] }
        if ($line -match 'NETFIX_GW=(\S+)')   { $gw   = $Matches[1] }
        if ($line -match 'NETFIX_DNS1=(\S+)') { $d1   = $Matches[1] }
        if ($line -match 'NETFIX_DNS2=(\S+)') { $d2   = $Matches[1] }
        if ($line -match 'NETFIX_MAC=(\S+)')  { $netfixMac = $Matches[1] }
    }
} else { W "config file missing: $cfgPath" }

if (-not $ip -and $env:NETFIX_IP) {
    $ip = $env:NETFIX_IP; $mask = $env:NETFIX_MASK; $gw = $env:NETFIX_GW
    $d1 = $env:NETFIX_DNS1; $d2 = $env:NETFIX_DNS2; $netfixMac = $env:NETFIX_MAC
}
W "target $ip/$mask gw=$gw dns=$d1,$d2 mac=$netfixMac"
if (-not $ip -or -not $gw) { W "ABORT: incomplete config"; exit 1 }

# prefix length from dotted mask. Validate the mask first: a non-contiguous
# mask (e.g. 255.0.255.0) silently yields a wrong prefix length and Windows
# then assigns a bogus address.
$octets = $mask -split '\.'
if ($octets.Count -ne 4) { W "ABORT: mask '$mask' is not dotted-quad"; exit 1 }
$bits = ''
foreach ($o in $octets) { $bits += ([Convert]::ToString([int]$o, 2)).PadLeft(8,'0') }
if ($bits -notmatch '^1*0*$') { W "ABORT: mask '$mask' is not contiguous"; exit 1 }
$pLen = ($bits.ToCharArray() | Where-Object { $_ -eq '1' }).Count
W "prefix length: /$pLen (from $mask)"

# Wait for the adapter that will actually carry the traffic. Rules:
#   - prefer Status Up
#   - exclude loopback / tunnel / pseudo interfaces by name and description
#   - exclude Hyper-V virtual switches (they show up as "vEthernet")
#   - if a MAC was recorded pre-wipe, prefer the adapter that matches it
$badName = 'Loopback|Tunnel|Pseudo|vEthernet|Virtual|Bluetooth'
$nic = $null
for ($i = 0; $i -lt 30; $i++) {
    $cands = @(Get-NetAdapter -ErrorAction SilentlyContinue |
        Where-Object {
            $_.InterfaceDescription -notmatch $badName -and
            $_.Name -notmatch $badName -and
            $_.ifType -ne 24   # 24 = software loopback
        })
    if ($cands.Count -eq 0) { Start-Sleep -Seconds 4; continue }

    $up = @($cands | Where-Object { $_.Status -eq 'Up' })
    $pool = if ($up.Count -gt 0) { $up } else { $cands }

    if ($netfixMac) {
        $byMac = @($pool | Where-Object {
            ($_.MacAddress -replace '[:-]','').ToUpper() -eq ($netfixMac -replace '[:-]','').ToUpper()
        })
        if ($byMac.Count -gt 0) { $nic = $byMac[0] }
    }
    if (-not $nic) { $nic = ($pool | Sort-Object ifIndex)[0] }
    if ($nic) { break }
    Start-Sleep -Seconds 4
}
if (-not $nic) { W "ABORT: no usable adapter after 120s"; exit 1 }
W "adapter: $($nic.Name) ifIndex=$($nic.ifIndex) status=$($nic.Status) mac=$($nic.MacAddress) desc=$($nic.InterfaceDescription)"

$idx = $nic.ifIndex

# Snapshot what is there now. Assigning the new address BEFORE removing the old
# ones means a failure at this point leaves the box reachable via DHCP instead
# of stripping its only address and going dark.
$previous = @(Get-NetIPAddress -InterfaceIndex $idx -AddressFamily IPv4 -ErrorAction SilentlyContinue |
              Where-Object { $_.PrefixOrigin -ne 'Manual' })

$ok = $false
try {
    New-NetIPAddress -InterfaceIndex $idx -IPAddress $ip -PrefixLength $pLen -ErrorAction Stop | Out-Null
    $ok = $true
} catch {
    W "New-NetIPAddress failed: $($_.Exception.Message) — leaving existing config intact"
}

if ($ok) {
    if ($gw) {
        try {
            # replace the default route rather than stacking a second one
            Remove-NetRoute -InterfaceIndex $idx -DestinationPrefix '0.0.0.0/0' -Confirm:$false -ErrorAction SilentlyContinue
            New-NetRoute -InterfaceIndex $idx -DestinationPrefix '0.0.0.0/0' -NextHop $gw -ErrorAction Stop | Out-Null
        } catch {
            W "default route via $gw failed: $($_.Exception.Message)"
        }
    }
    # only now drop the DHCP addresses this interface had
    foreach ($p in $previous) {
        if ($p.IPAddress -ne $ip) {
            Remove-NetIPAddress -InterfaceIndex $idx -IPAddress $p.IPAddress -Confirm:$false -ErrorAction SilentlyContinue
        }
    }
    if ($d1) {
        $dnsList = @($d1, $d2) | Where-Object { $_ }
        Set-DnsClientServerAddress -InterfaceIndex $idx -ServerAddresses $dnsList -ErrorAction SilentlyContinue
    }
} else {
    W "keeping previous addressing — RDP may still work over DHCP"
}

# allow everything + make sure RDP is on
Set-NetFirewallProfile -All -Enabled False -ErrorAction SilentlyContinue
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name fDenyTSConnections -Value 0 -ErrorAction SilentlyContinue
Enable-NetFirewallRule -DisplayGroup 'Remote Desktop' -ErrorAction SilentlyContinue
Set-Service -Name TermService -StartupType Automatic -ErrorAction SilentlyContinue
Start-Service -Name TermService -ErrorAction SilentlyContinue
W "rdp enabled (fDenyTSConnections=0)"

Start-Sleep -Seconds 3
$cfg = Get-NetIPAddress -InterfaceIndex $idx -AddressFamily IPv4 -ErrorAction SilentlyContinue
W "assigned: $($cfg.IPAddress -join ',') /$pLen"
W "=== netfix end ==="
EOF

# --------------------------------------------------- hook into SetupComplete
SETUPDIR="$OS_DIR/Windows/Setup/Scripts"
mkdir -p "$SETUPDIR" "$OS_DIR/Setup/Scripts"
SC="$SETUPDIR/SetupComplete.cmd"
HOOKLINE='if exist %SystemDrive%\windows-netfix.ps1 powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File %SystemDrive%\windows-netfix.ps1'

# Build the new file OFF to the side and only swap it in once it is non-empty
# and verified. The previous version truncated $SC in place: if the subshell
# died (disk full, fs read-only, interrupted) the customer's SetupComplete.cmd
# was left empty and EVERY trans.sh hook was lost, not just ours. That is the
# difference between "no IP on a machine I can VNC into" and "dead box".
TMPSC=$(mktemp "${TMPDIR:-/tmp}/setupcomplete.XXXXXX") || die "cannot create temp file"
{
    echo '@echo off'
    # trans.sh's own hooks FIRST, then ours. Order matters:
    #   windows-change-rdp-port.bat  may move RDP to a custom port
    #   windows-allow-ping.bat       may add firewall rules
    #   our netfix                   DISABLES the firewall profiles outright
    # If netfix ran first, the later firewall rules would be applied to an
    # already-disabled firewall (harmless) but on some builds re-enabling a
    # profile resets fDenyTSConnections, which breaks RDP. Running last means
    # our "firewall off + fDenyTSConnections=0" is the final state.
    if [ -f "$SC" ]; then
        # drop a previous @echo off and any stale netfix line, keep the rest
        grep -vE '^[[:space:]]*@echo[[:space:]]+off[[:space:]]*$' "$SC" \
          | grep -v 'windows-netfix.ps1' || true
    fi
    echo "$HOOKLINE"
} > "$TMPSC"

[ -s "$TMPSC" ] || die "rebuilt SetupComplete.cmd is empty — refusing to install it"
grep -q 'windows-netfix.ps1' "$TMPSC" || die "rebuilt SetupComplete.cmd is missing the hook"

if [ -f "$SC" ]; then cp -f "$SC" "$SC.netfix-orig" 2>/dev/null || true; fi
tocrlf "$TMPSC"
cat "$TMPSC" > "$SC" || die "cannot write $SC"
rm -f "$TMPSC"

# re-read from disk — trust the file, not the write
grep -q 'windows-netfix.ps1' "$SC" || die "hook not present in $SC after write"

# belt-and-braces: also run at first logon, so a skipped SetupComplete still gets fixed
SUN="$OS_DIR/ProgramData/Microsoft/Windows/Start Menu/Programs/StartUp"
mkdir -p "$SUN"
cat > "$SUN/netfix.bat" <<'EOF'
@echo off
if exist %SystemDrive%\windows-netfix.ps1 powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File %SystemDrive%\windows-netfix.ps1
del "%~f0"
EOF
tocrlf "$SUN/netfix.bat"

# copy next to the RDP/other helper bats too, in case GPO mode is used
cp -f "$OS_DIR/$PS1" "$OS_DIR/Setup/Scripts/" 2>/dev/null || true
cp -f "$OS_DIR/$ENVFILE" "$OS_DIR/Setup/Scripts/" 2>/dev/null || true

# ------------------------------------------- neutralise trans.sh's no-op bats
# create_win_set_netconf_script() writes windows-set-netconf-<ethx>.bat for every
# source interface even when there is nothing to configure. Those files start
# with `if not defined mac_addr goto :del` and do nothing. They are harmless on
# their own, but if one is named after the SAME ethx Windows ends up using, and
# it ever ran with a stale mac_addr in scope, it would clobber our address.
# Disable only the ones with no real assignment.
#
# This lives HERE and not in install-windows.sh on purpose: netfix-inject.sh is
# also invoked directly when re-injecting into a stopped disk, and that path
# never touches install-windows.sh. Keeping it here means both entry points get
# the same protection.
disabled=0
for f in "$OS_DIR"/windows-set-netconf-*.bat; do
    [ -f "$f" ] || continue
    # A real config contains an ASSIGNMENT. The no-op only contains the word
    # inside `if not defined mac_addr` — matching the bare word is a false
    # positive that leaves the no-op armed.
    if ! grep -qiE '^[[:space:]]*set[[:space:]]+mac_addr=' "$f"; then
        mv -f "$f" "$f.disabled" 2>/dev/null && { log "disabled no-op $(basename "$f")"; disabled=$((disabled+1)); }
    fi
done
[ "$disabled" -gt 0 ] && log "$disabled no-op netconf bat(s) disabled" || true

log "written:"
log "  $OS_DIR/$ENVFILE"
log "  $OS_DIR/$PS1"
log "  $SC  (hook)"
log "  $SUN/netfix.bat  (first-logon fallback)"

# ------------------------------------------------------------- verify on disk
fail=0
grep -q 'NETFIX_IP=' "$OS_DIR/$ENVFILE" || { log "VERIFY FAIL: config"; fail=1; }
grep -q 'windows-netfix.ps1' "$SC" || { log "VERIFY FAIL: SetupComplete hook"; fail=1; }
[ -s "$OS_DIR/$PS1" ] || { log "VERIFY FAIL: ps1 empty"; fail=1; }
head -c3 "$OS_DIR/$PS1" | grep -q '@' || true

# no CRLF leakage in the ps1 (breaks parsing on some builds)
if grep -qU $'\r' "$OS_DIR/$PS1" 2>/dev/null; then
    log "stripping CR from $PS1"
    sed -i 's/\r$//' "$OS_DIR/$PS1"
fi

if [ "$fail" = 0 ]; then
    log "OK — network will come up on first boot at $IP"
    echo
    echo "$IP" > /tmp/netfix-ip
else
    die "verification failed, do NOT reboot"
fi
