#!/bin/bash
# netfix-wim.sh — inject static-IP config DIRECTLY INTO install.wim.
#
# This is the CORRECT injection point, established by reading trans.sh on a live
# run (2026-11-14), replacing the earlier /os-based approach which was WRONG:
#
#   * trans.sh does NOT apply Windows to /os. It stages an installer:
#       /os/bootmgr, /os/sources/boot.wim, /os/installer/sources/install.wim
#     WinPE applies install.wim on FIRST BOOT. So at hold-2 time /os has no
#     Windows/Setup/Scripts/SetupComplete.cmd at all, and anything written there
#     is discarded when the disk is actually written.
#
#   * The real SetupComplete.cmd lives INSIDE install.wim at
#       /Windows/Setup/Scripts/SetupComplete.cmd
#     and trans.sh already put its own hooks in it (allow-ping, resize,
#     set-netconf-eth0, no-lockout-threshold).
#
#   * The root-cause file is /windows-set-netconf-eth0.bat inside the same WIM.
#     Every `set mac_addr=` line in it is prefixed with `rem`, so mac_addr is
#     never defined, and the script hits
#         if not defined mac_addr goto :del
#     and exits doing nothing. That is why the guest boots with no address.
#
# So this script:
#   1. extracts the real SetupComplete.cmd from the WIM
#   2. prepends our hook (kept last in run order, see below)
#   3. writes windows-netfix-config.bat + windows-netfix.ps1 into the WIM root
#   4. runs `wimlib-imagex update` to put all three back
#   5. verifies by RE-EXTRACTING and reading the result back
#
# No fuse needed (fusermount3 is absent from the Alpine netboot), so this works
# inside the installer environment.
#
# Usage: bash netfix-wim.sh <WIM> <INDEX> [--os-dir /os]
#   network values are read from /root/net-backup/network.txt (or /net-backup/)

set -uo pipefail

WIM=${1:-}
INDEX=${2:-}
OS_DIR=${3:-/os}

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

[ -n "$WIM" ]   || die "usage: netfix-wim.sh <WIM> <INDEX>"
[ -n "$INDEX" ] || die "index required"
[ -f "$WIM" ]   || die "$WIM not found"
command -v wimlib-imagex >/dev/null || die "wimlib-imagex missing (apk add wimlib)"

W=$(mktemp -d /tmp/netfixwim.XXXXXX) || die "mktemp failed"
trap 'rm -rf "$W"' EXIT

# ---------------------------------------------------------------- read config
NB=/root/net-backup/network.txt
[ -f "$NB" ] || NB=/net-backup/network.txt
[ -f "$NB" ] || NB=/tmp/network.txt
[ -f "$NB" ] || die "no captured network config ($NB) — run preflight-scan.sh first"
# shellcheck disable=SC1090
. "$NB"

IP=${WINDOWS_IP:-$IP}
PREFIX=${PREFIX:-}
GW=${GW:-}
MAC=${MAC:-}
DNS1=${DNS1:-183.60.83.19}
DNS2=${DNS2:-8.8.8.8}

[ -n "$IP" ] && [ -n "$GW" ] || die "IP/GW missing from $NB"
[ -n "$PREFIX" ] || die "PREFIX missing from $NB"

# NAT guard — public IP on the NIC would take the box dark
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 ] && ! is_private "$IP"; then
    die "host is NAT but IP=$IP is public — refusing (would break the return path)"
fi

# prefix -> mask, full /0../32
prefix_to_mask() {
    p=$1
    [ "$p" -ge 0 ] 2>/dev/null && [ "$p" -le 32 ] 2>/dev/null || return 1
    local filled=$((p/8)) rest=$((p%8)) i=0 octet mask=""
    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") || die "bad prefix /$PREFIX"

# gateway must be inside the subnet
ip_to_hex() { local IFS=. o; for o in $1; do printf '%02x' "$o"; done; }
va() {
    local a=$1 p=$2 g=$3 an gn m
    _ipn=$((0x$(ip_to_hex "$a"))); _gwn=$((0x$(ip_to_hex "$g")))
    if [ "$p" -eq 0 ]; then m=0; else m=$(( (0xFFFFFFFF << (32-p)) & 0xFFFFFFFF )); fi
    [ $(( _gwn & m )) -eq $(( _ipn & m )) ]
}
va "$IP" "$PREFIX" "$GW" || die "gateway $GW not inside $IP/$PREFIX — Windows would reject this silently"

log "config: ip=$IP mask=$MASK gw=$GW mac=${MAC:-none} dns=$DNS1,$DNS2"
log "wim: $WIM index $INDEX"

# ------------------------------------------------------- extract real files
wimlib-imagex extract "$WIM" "$INDEX" "/Windows/Setup/Scripts/SetupComplete.cmd" --dest-dir="$W/ext" >/dev/null 2>&1
SC="$W/ext/SetupComplete.cmd"
if [ -f "$SC" ]; then
    log "existing SetupComplete.cmd: $(wc -c <"$SC") bytes"
else
    warn "no SetupComplete.cmd in image — creating one"
    mkdir -p "$W/ext"; printf '@echo off\r\n' > "$SC"
fi

# ---------------------------------------------------------------- build files
# config: plain `set VAR=` lines, CRLF, cmd.exe safe
CFG="$W/ext/windows-netfix-config.bat"
{
    echo '@echo off'
    echo "rem netfix config generated $(date -u +%Y-%m-%dT%H:%M:%SZ)"
    echo "set NETFIX_IP=$IP"
    echo "set NETFIX_MASK=$MASK"
    echo "set NETFIX_GW=$GW"
    echo "set NETFIX_DNS1=$DNS1"
    echo "set NETFIX_DNS2=$DNS2"
    echo "set NETFIX_MAC=$MAC"
} > "$CFG"

# PowerShell does the actual work
PS1="$W/ext/windows-netfix.ps1"
cat > "$PS1" <<'PSEOF'
$ErrorActionPreference = 'Continue'
$log = "$env:SystemDrive\netfix-result.txt"
function W($m) { "$([DateTime]::Now.ToString('yyyy-MM-dd HH:mm:ss')) $m" | Tee-Object -FilePath $log -Append }

W "=== netfix start ==="

# read config from disk: `set VAR=` in a .bat is NOT an env var for a separate
# PowerShell process, so env lookup alone yields an empty config.
$cfgPath = "$env:SystemDrive\windows-netfix-config.bat"
$ip=''; $mask=''; $gw=''; $d1=''; $d2=''; $macSrc=''
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+)')  { $macSrc = $Matches[1] }
    }
} else { W "config missing: $cfgPath" }

W "target ip=$ip mask=$mask gw=$gw mac=$macSrc dns=$d1,$d2"
if (-not $ip -or -not $gw -or -not $mask) { W "ABORT: incomplete config"; exit 1 }

# dotted mask -> prefix length, reject non-contiguous masks
$oct = $mask -split '\.'
if ($oct.Count -ne 4) { W "ABORT: mask $mask not dotted-quad"; exit 1 }
$bits = ''
foreach ($o in $oct) { $bits += ([Convert]::ToString([int]$o, 2)).PadLeft(8,'0') }
if ($bits -notmatch '^1*0*$') { W "ABORT: mask $mask not contiguous"; exit 1 }
$pLen = ($bits.ToCharArray() | Where-Object { $_ -eq '1' }).Count
W "prefix /$pLen"

# virtio NIC driver may still be loading on first boot — poll
$bad = 'Loopback|Tunnel|Pseudo|vEthernet|Virtual|Bluetooth'
$nic = $null
for ($i=0; $i -lt 30; $i++) {
    $c = @(Get-NetAdapter -ErrorAction SilentlyContinue | Where-Object {
        $_.InterfaceDescription -notmatch $bad -and $_.Name -notmatch $bad -and $_.ifType -ne 24
    })
    if ($c.Count -eq 0) { Start-Sleep -Seconds 4; continue }
    $up = @($c | Where-Object { $_.Status -eq 'Up' })
    $pool = if ($up.Count -gt 0) { $up } else { $c }
    if ($macSrc) {
        $byMac = @($pool | Where-Object {
            ($_.MacAddress -replace '[:-]','').ToUpper() -eq ($macSrc -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)"

$idx = $nic.ifIndex
$prev = @(Get-NetIPAddress -InterfaceIndex $idx -AddressFamily IPv4 -ErrorAction SilentlyContinue |
          Where-Object { $_.PrefixOrigin -ne 'Manual' })

# assign BEFORE removing: a failure here must not leave the box with no address
$ok = $false
try {
    New-NetIPAddress -InterfaceIndex $idx -IPAddress $ip -PrefixLength $pLen -ErrorAction Stop | Out-Null
    $ok = $true
} catch { W "New-NetIPAddress failed: $($_.Exception.Message)" }

if ($ok) {
    try {
        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 "route via $gw failed: $($_.Exception.Message)" }
    foreach ($p in $prev) {
        if ($p.IPAddress -ne $ip) {
            Remove-NetIPAddress -InterfaceIndex $idx -IPAddress $p.IPAddress -Confirm:$false -ErrorAction SilentlyContinue
        }
    }
    if ($d1) {
        Set-DnsClientServerAddress -InterfaceIndex $idx -ServerAddresses (@($d1,$d2) | Where-Object {$_}) -ErrorAction SilentlyContinue
    }
} else { W "keeping existing addressing" }

# firewall off + RDP 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"

# also drop the first-logon fallback so a skipped SetupComplete still gets fixed
$startup = "$env:ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"
if (Test-Path $startup) {
    @(
      '@echo off',
      'if exist %SystemDrive%\windows-netfix.ps1 powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File %SystemDrive%\windows-netfix.ps1',
      'del "%~f0"'
    ) -join "`r`n" | Set-Content -Path (Join-Path $startup 'netfix.bat') -Encoding ASCII
}

Start-Sleep -Seconds 3
$got = Get-NetIPAddress -InterfaceIndex $idx -AddressFamily IPv4 -ErrorAction SilentlyContinue
W "assigned: $($got.IPAddress -join ',') /$pLen"
$gwOk = Test-NetConnection -ComputerName $gw -InformationLevel Quiet -WarningAction SilentlyContinue
W "gateway reachable: $gwOk"
W "=== netfix end ==="
PSEOF

# CRLF for the .bat files (idempotent: strip then add exactly one CR)
crlf() {
    local f=$1
    local t="$f.tmp.$$"
    sed 's/\r$//' "$f" | sed 's/$/\r/' > "$t" && mv "$t" "$f"
}
crlf "$CFG"
crlf "$SC"

# ------------------------------------------------------------ rebuild hook
# Order: trans.sh hooks first, ours LAST. Ours disables firewall profiles, so it
# must be the final state (a later profile re-enable can reset fDenyTSConnections).
HOOK='if exist %SystemDrive%\windows-netfix.ps1 powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File %SystemDrive%\windows-netfix.ps1'

TMP="$W/new_sc.cmd"
{
    echo '@echo off'
    # keep every existing line except a previous @echo off / stale netfix line
    grep -vE '^[[:space:]]*@echo[[:space:]]+off[[:space:]]*$' "$SC" | grep -v 'windows-netfix.ps1' || true
    echo "$HOOK"
} > "$TMP"
crlf "$TMP"

[ -s "$TMP" ] || die "rebuilt SetupComplete.cmd is empty"
grep -q 'windows-netfix.ps1' "$TMP" || die "hook missing from rebuilt file"
grep -q 'windows-set-netconf' "$TMP" && log "trans.sh netconf hooks preserved"

cp -f "$TMP" "$SC"

# --------------------------------------------------------- neutralise no-ops
# The root-cause file: every set mac_addr= is commented out, so the bat exits at
# `if not defined mac_addr goto :del`. Easiest durable fix is to ACTIVATE the
# config in it rather than disable it — that keeps trans.sh's calling convention
# (it is already called from SetupComplete.cmd) and makes the address apply even
# if our PowerShell hook is somehow skipped.
NC="$W/ext/windows-set-netconf.bat"
if wimlib-imagex extract "$WIM" "$INDEX" "/windows-set-netconf-eth0.bat" --dest-dir="$W/nc" >/dev/null 2>&1; then
    SRC=$(find "$W/nc" -name 'windows-set-netconf-eth0.bat' | head -1)
    if [ -n "$SRC" ]; then
        # strip the `rem ` in front of the ipv4 settings, inject our values
        sed -E \
          -e "s|^rem set mac_addr=.*|set mac_addr=$MAC|" \
          -e "s|^rem set ipv4_addr=.*|set ipv4_addr=$IP/$PREFIX|" \
          -e "s|^rem set ipv4_gateway=.*|set ipv4_gateway=$GW|" \
          -e "s|^rem set ipv4_dns1=.*|set ipv4_dns1=$DNS1|" \
          -e "s|^rem set ipv4_dns2=.*|set ipv4_dns2=$DNS2|" \
          "$SRC" > "$NC"
        crlf "$NC"
        log "activated trans.sh netconf bat (mac=$MAC ip=$IP/$PREFIX gw=$GW)"
    fi
fi

# --------------------------------------------------------------- apply to WIM
# wimlib accepts only ONE --command; the rest must go on stdin. Passing several
# --command flags aborts with "--command may only be specified one time".
log "updating $WIM (index $INDEX) — this rewrites ~3.9 GB, be patient"
{
    echo "add $CFG /windows-netfix-config.bat"
    echo "add $PS1 /windows-netfix.ps1"
    echo "add $SC /Windows/Setup/Scripts/SetupComplete.cmd"
    if [ -f "$NC" ]; then echo "add $NC /windows-set-netconf-eth0.bat"; fi
} > "$W/update.cmds"

cat "$W/update.cmds"
if ! wimlib-imagex update "$WIM" "$INDEX" < "$W/update.cmds" 2>&1 | tail -20; then
    die "wimlib update failed"
fi

# ------------------------------------------------------------------- verify
log "verifying by re-extracting from the WIM"
V="$W/verify"
rm -rf "$V"
wimlib-imagex extract "$WIM" "$INDEX" "/Windows/Setup/Scripts/SetupComplete.cmd" --dest-dir="$V" >/dev/null 2>&1
VSC="$V/SetupComplete.cmd"
[ -f "$VSC" ] || die "verify: SetupComplete.cmd not readable back"
grep -q 'windows-netfix.ps1' "$VSC" || die "verify: hook NOT in SetupComplete.cmd"
n=$(grep -c 'windows-netfix.ps1' "$VSC")
[ "$n" = 1 ] || die "verify: hook appears $n times (expected 1)"
log "hook verified in SetupComplete.cmd (1 occurrence)"

rm -rf "$V"
wimlib-imagex extract "$WIM" "$INDEX" "/windows-netfix-config.bat" --dest-dir="$V" >/dev/null 2>&1
[ -f "$V/windows-netfix-config.bat" ] || die "verify: config not in WIM"
grep -q "NETFIX_IP=$IP" "$V/windows-netfix-config.bat" || die "verify: config IP mismatch"
log "config verified in WIM: $(grep NETFIX_IP "$V/windows-netfix-config.bat")"

rm -rf "$V"
wimlib-imagex extract "$WIM" "$INDEX" "/windows-netfix.ps1" --dest-dir="$V" >/dev/null 2>&1
[ -s "$V/windows-netfix.ps1" ] || die "verify: ps1 not in WIM"
log "ps1 verified in WIM ($(wc -c <"$V/windows-netfix.ps1") bytes)"

if [ -f "$NC" ]; then
    rm -rf "$V"
    wimlib-imagex extract "$WIM" "$INDEX" "/windows-set-netconf-eth0.bat" --dest-dir="$V" >/dev/null 2>&1
    if grep -q "^set mac_addr=$MAC" "$V/windows-set-netconf-eth0.bat" 2>/dev/null; then
        log "trans.sh netconf bat verified active (mac_addr set)"
    else
        warn "trans.sh netconf bat did not verify active — PowerShell hook is the primary path"
    fi
fi

echo
log "=== WIM INJECTION COMPLETE ==="
log "Windows will configure $IP/$PREFIX gw=$GW on first boot, before login."
log "Now reboot."
