#!/bin/bash
# install-windows.sh — Linux VPS -> Windows + working RDP, DHCP-provider safe.
#
# Verified against bin456789/reinstall trans.sh semantics:
#   * --hold 2 runs trans(), then `exit` before `reboot` (trans.sh:9144-9152).
#     Disk ends up mounted at /os; nothing reboots into the new OS.
#   * trans() REWRITES SetupComplete.cmd (trans.sh:3816-3825), so any hook we
#     write must land AFTER trans() finishes. Injecting first = hook destroyed.
#   * create_win_set_netconf_script() (trans.sh:6461) only emits mac_addr when the
#     SOURCE system had a static IP. On a DHCP VPS nothing is written and
#     windows-set-netconf.bat exits at `if not defined mac_addr goto :del`.
#     => Windows boots with no address, every port filtered. This wrapper exists
#        to close that hole.
#
# Runs ON THE TARGET as root. Usage:
#   bash install-windows.sh --iso URL --image "NAME" [--pass PASS] [--hold]
#   bash install-windows.sh --after-hold        # stage 2, run from Alpine
set -uo pipefail

ISO_URL=""
IMAGE_NAME=""
RDP_PASS="${RDP_PASS:-Masuk123!}"
RDP_PORT=3389
USERNAME=administrator
HOLD=2
AFTER_HOLD=0
IP=""; PREFIX=""; GW=""; DNS1=""; DNS2=""
REPO="${REPO:-http://rdp.gracexz.my.id}"
# Origin langsung untuk fetch helper (netfix-inject.sh). Default sama dengan REPO,
# tapi runner menimpanya lewat env REPO_ORIGIN supaya gak lewat Cloudflare.
REPO_ORIGIN="${REPO_ORIGIN:-}"

while [ $# -gt 0 ]; do
    case "$1" in
        --iso) ISO_URL=$2; shift 2 ;;
        --image) IMAGE_NAME=$2; shift 2 ;;
        --pass) RDP_PASS=$2; shift 2 ;;
        --port) RDP_PORT=$2; shift 2 ;;
        --user) USERNAME=$2; shift 2 ;;
        --ip) IP=$2; shift 2 ;;
        --prefix) PREFIX=$2; shift 2 ;;
        --gw) GW=$2; shift 2 ;;
        --dns1) DNS1=$2; shift 2 ;;
        --dns2) DNS2=$2; shift 2 ;;
        --hold) HOLD=$2; shift 2 ;;
        --repo) REPO_ORIGIN=$2; shift 2 ;;
        --after-hold) AFTER_HOLD=1; shift ;;
        *) echo "unknown arg: $1" >&2; exit 2 ;;
    esac
done

log()  { echo -e "\033[1;36m[install]\033[0m $*"; }
warn() { echo -e "\033[1;33m[install]\033[0m $*"; }
die()  { echo -e "\033[1;31m[install] FATAL:\033[0m $*" >&2; exit 1; }

# ============================================================ STAGE 2 (Alpine)
if [ "$AFTER_HOLD" = 1 ]; then
    log "=== STAGE 2: post-install injection (running inside Alpine) ==="

    # --- verify trans() actually finished -------------------------------
    [ -f /reinstall.log ] || die "/reinstall.log missing — trans() never ran"
    if ! grep -qE 'DONE|hold 2' /reinstall.log; then
        die "trans() did not reach completion. Tail:
$(tail -20 /reinstall.log)"
    fi
    log "trans() complete: $(grep -cE 'DONE' /reinstall.log) done-marker(s)"

    # --- verify /os is a real Windows tree, not just the extracted ISO ---
    for p in /os/Windows/System32 /os/Users /os/ProgramData; do
        [ -d "$p" ] || die "$p missing — /os does not look like an installed Windows"
    done
    if [ -d /os/sources ] && [ ! -d /os/Windows/System32 ]; then
        die "/os holds the ISO payload, not an installed Windows — install did not apply"
    fi
    log "/os verified as an installed Windows tree"

    # --- inject static network + RDP (the whole point of --hold 2) -------
    INJ=/root/netfix-inject.sh
    [ -f "$INJ" ] || {
        SRC_BASE="${REPO_ORIGIN:-$REPO}"
        log "fetching netfix-inject.sh from $SRC_BASE"
        curl -fsSL -o "$INJ" "$SRC_BASE/scripts/netfix-inject.sh" \
            || curl -fsSL -o "$INJ" "$REPO/scripts/netfix-inject.sh" \
            || die "cannot fetch netfix-inject.sh"
    }

    # Prefer the network captured in stage 1 — that is the authoritative record
    # of what the box had before the disk was wiped. Alpine's live view can
    # differ (different NIC name, transient DHCP lease) and /dev/netconf may be
    # gone by now.
    NB=/root/net-backup/network.txt
    [ -f "$NB" ] || NB=/net-backup/network.txt
    if [ -f "$NB" ]; then
        log "using captured network config: $NB"
        # shellcheck disable=SC1090
        . "$NB"
    else
        warn "no captured network config found — relying on autodetect"
    fi

    # explicit args only when we genuinely have both halves; a lone --prefix
    # must not be silently dropped (that was a real bug: user passes
    # --prefix 22, expects /22, gets whatever autodetect found).
    [ -z "$IP" ] || [ -n "$PREFIX" ] || die "--ip $IP given without --prefix"
    if [ -n "$IP" ] && [ -n "$PREFIX" ]; then
        [ -n "$GW" ] || die "--ip given without --gw"
        log "explicit network: $IP/$PREFIX gw=$GW"
        OS_DIR=/os MAC="${MAC:-}" bash "$INJ" "$IP" "$PREFIX" "$GW" \
            "${DNS1:-183.60.83.19}" "${DNS2:-8.8.8.8}" || die "netfix injection failed"
    else
        log "autodetect mode (no --ip/--prefix given)"
        OS_DIR=/os MAC="${MAC:-}" IP="$IP" PREFIX="$PREFIX" GW="$GW" \
            bash "$INJ" || die "netfix injection failed (autodetect)"
    fi

    # --- post-injection proof -------------------------------------------
    SC=/os/Windows/Setup/Scripts/SetupComplete.cmd
    grep -q 'windows-netfix.ps1' "$SC" || die "SetupComplete.cmd hook missing after inject"
    grep -q 'NETFIX_IP=' /os/windows-netfix-config.bat || die "config file missing after inject"
    log "hook present in SetupComplete.cmd"
    log "injected IP: $(grep NETFIX_IP /os/windows-netfix-config.bat)"

    # --- neutralise the upstream no-op so it cannot run later and clobber --
    # NOTE: a no-op file still CONTAINS the string "mac_addr" (in
    # `if not defined mac_addr goto :del`), so match the ASSIGNMENT form only.
    for f in /os/windows-set-netconf-*.bat; do
        [ -f "$f" ] || continue
        if ! grep -qiE '^[[:space:]]*set[[:space:]]+mac_addr=' "$f"; then
            mv "$f" "$f.disabled"
            log "disabled no-op $(basename "$f") (no mac_addr assignment)"
        fi
    done

    echo
    log "=== STAGE 2 COMPLETE ==="
    log "Reboot now to boot Windows. It will self-configure $({ grep -o '[0-9.]*/[0-9]*' /os/windows-netfix-config.bat 2>/dev/null || echo "its IP"; } | head -1) before login."
    log "After reboot expect: ttl=125, 3389 open."
    exit 0
fi

# ========================================================== STAGE 1 (Linux)
log "=== STAGE 1: stage the reinstall (running on Linux) ==="

[ "$(id -u)" = 0 ] || die "must run as root"

command -v curl >/dev/null || die "curl missing"
command -v ip   >/dev/null || die "iproute2 missing"

# --- feasibility ---------------------------------------------------------
nested=$(grep -oE '(vmx|svm)' /proc/cpuinfo 2>/dev/null | sort -u | tr '\n' ' ')
[ -z "$nested" ] && log "no nested KVM (expected on cloud VPS) — reinstall.sh is the right path"
[ -d /sys/firmware/efi ] && BOOTMODE=UEFI || BOOTMODE=BIOS
log "firmware: $BOOTMODE"

virtio=$(lsblk -o NAME,TRAN 2>/dev/null | grep -c virtio || true)
[ "$virtio" -gt 0 ] && log "virtio disk detected — drivers must be present in the image"

vendor=$(cat /sys/devices/virtual/dmi/id/sys_vendor 2>/dev/null || echo unknown)
log "vendor: $vendor"
[ "$vendor" = "Tencent Cloud" ] && log "Tencent Cloud detected — edge firewall needs 3389 open (product-level, not ufw)"

# --- capture network BEFORE anything is wiped ----------------------------
if [ -z "$IP" ]; then
    iface=$(ip route 2>/dev/null | awk '/^default/{print $5; exit}')
    [ -n "$iface" ] || die "no default route — cannot determine network"
    cidr=$(ip -4 -o addr show dev "$iface" | awk '{print $4}' | head -1)
    [ -n "$cidr" ] || die "no IPv4 on $iface"
    IP=${cidr%%/*}; PREFIX=${cidr##*/}
    GW=${GW:-$(ip route | awk '/^default/{print $3; exit}')}
    log "captured from $iface: $IP/$PREFIX gw=$GW"
else
    log "using supplied network: $IP/${PREFIX:-?} gw=${GW:-?}"
fi

if [ -z "$DNS1" ]; then
    DNS1=$(awk '/^nameserver/{print $2}' /etc/resolv.conf 2>/dev/null | grep -vE '^(127\.|::1)' | head -1)
    DNS2=$(awk '/^nameserver/{print $2}' /etc/resolv.conf 2>/dev/null | grep -vE '^(127\.|::1)' | sed -n 2p)
    [ -n "$DNS1" ] || DNS1=183.60.83.19
    [ -n "$DNS2" ] || DNS2=8.8.8.8
fi

# persist so a rollback can restore it
mkdir -p /root/net-backup
{ echo "IP=$IP"; echo "PREFIX=$PREFIX"; echo "GW=$GW"; echo "DNS1=$DNS1"; echo "DNS2=$DNS2"; } \
  > /root/net-backup/network.txt
log "network saved to /root/net-backup/network.txt"

# prove the gateway is reachable before wiping
ping -c1 -W3 "$GW" >/dev/null 2>&1 && log "gateway $GW reachable" || warn "gateway $GW did not answer ping (may still be fine)"

[ -n "$ISO_URL" ]    || die "--iso required"
[ -n "$IMAGE_NAME" ] || die "--image required"

# --- preflight: the image must be reachable and serve Range --------------
log "checking ISO reachability: $ISO_URL"
code=$(curl -s -o /dev/null -w '%{http_code}' -r 0-1023 "$ISO_URL" || echo 000)
[ "$code" = 206 ] || [ "$code" = 200 ] || die "ISO not reachable (HTTP $code)"
log "ISO reachable (HTTP $code)"

# --- disk space sanity ---------------------------------------------------
# Dua angka berbeda dan keduanya penting:
#   * ISO harus diunduh utuh  -> butuh ukuran ISO + ruang ekstra
#   * Windows harus di-apply  -> butuh ~12 GB setelah ISO diekstrak
# Berhenti di sini, SEBELUM satu byte pun ditulis, supaya tidak ada
# "gagal di tengah" yang bikin target menggantung.
free_gb=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
free_gb=${free_gb:-0}
[ "$free_gb" -ge 8 ] || die "DISK KURANG: butuh minimal 8 GB free untuk apply Windows, tersedia cuma ${free_gb} GB. Perbesar disk VPS dulu."

# --- pre-download ISO secara PARALEL ------------------------------------
# Kenapa: TCP single-stream ke origin cuma ~300 KB/s (bottleneck per-koneksi,
# bukan bandwidth). 4 koneksi paralel = ~3 MB/s. reinstall.sh sendiri sedot
# ISO pakai wget single-stream, jadi 5 GB butuh 4+ jam dan sering mati di
# tengah. Kita sedot dulu paralel ke file lokal, lalu serahkan ke reinstall.sh
# lewat file:// biar dia cuma baca dari disk.
ISO_LOCAL=/root/win.iso
ISO_SIZE=$(curl -sI "$ISO_URL" | tr -d '\r' | awk 'tolower($1)=="content-length:"{print $2}' | tail -1)
if [ -z "$ISO_SIZE" ] || [ "$ISO_SIZE" -lt 1000000 ] 2>/dev/null; then
    warn "content-length tidak terbaca — fallback: biarkan reinstall.sh unduh sendiri"
else
    need_gb=$(( (ISO_SIZE / 1073741824) + 2 ))
    if [ "${free_gb:-0}" -lt "$need_gb" ]; then
        die "DISK KURANG: pre-download ISO butuh ~${need_gb} GB (ISO $((ISO_SIZE/1048576)) MB + overhead), tersedia cuma ${free_gb} GB. Perbesar disk VPS dulu."
    else
        log "pre-downloading ISO paralel: $ISO_URL ($((ISO_SIZE/1048576)) MB)"

        # resume kalau file parsial sudah ada
        have=0
        [ -f "$ISO_LOCAL" ] && have=$(stat -c%s "$ISO_LOCAL")
        if [ "$have" -eq "$ISO_SIZE" ]; then
            log "ISO lokal sudah lengkap, skip download"
        else
            [ "$have" -gt 0 ] && log "resume dari $((have/1048576)) MB"
            NCHUNK=16
            CHUNK=$(( (ISO_SIZE - have + NCHUNK - 1) / NCHUNK ))
            rm -f /root/.isochunk.*
            i=0
            while [ $i -lt $NCHUNK ]; do
                s=$(( have + i * CHUNK ))
                e=$(( s + CHUNK - 1 ))
                [ "$e" -ge "$ISO_SIZE" ] && e=$(( ISO_SIZE - 1 ))
                if [ "$s" -le "$e" ]; then
                    curl -fsSL --retry 8 --retry-delay 3 --retry-all-errors \
                         -r "$s-$e" "$ISO_URL" -o "/root/.isochunk.$i" &
                fi
                i=$((i+1))
            done
            wait
            # gabung chunk berurutan; gagal kalau ada yang hilang
            : > "$ISO_LOCAL.part"
            i=0
            while [ $i -lt $NCHUNK ]; do
                if [ -f "/root/.isochunk.$i" ]; then
                    cat "/root/.isochunk.$i" >> "$ISO_LOCAL.part"
                    rm -f "/root/.isochunk.$i"
                fi
                i=$((i+1))
            done
            got=$(stat -c%s "$ISO_LOCAL.part" 2>/dev/null || echo 0)
            if [ "$got" -eq "$ISO_SIZE" ]; then
                mv -f "$ISO_LOCAL.part" "$ISO_LOCAL"
                log "ISO lengkap: $ISO_LOCAL ($((got/1048576)) MB)"
            else
                warn "ukuran gabungan $got != $ISO_SIZE — fallback single-stream"
                mv -f "$ISO_LOCAL.part" "$ISO_LOCAL" 2>/dev/null
            fi
        fi

        if [ -f "$ISO_LOCAL" ] && [ "$(stat -c%s "$ISO_LOCAL")" -eq "$ISO_SIZE" ]; then
            ISO_URL="file://$ISO_LOCAL"
            log "reinstall.sh akan pakai ISO lokal (tanpa unduh ulang)"
        fi
    fi
fi

# --- disk space sanity (re-check setelah pre-download) -------------------
free_gb=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
[ "${free_gb:-0}" -ge 8 ] || die "need >=8 GB free on /, have ${free_gb}G"

# --- stage --hold 2 ------------------------------------------------------
cd /root || die "cannot cd /root"
[ -f reinstall.sh ] || curl -fsSL -o reinstall.sh https://raw.githubusercontent.com/bin456789/reinstall/main/reinstall.sh
chmod +x reinstall.sh

log "staging with --hold $HOLD (no reboot; disk mounted at /os when done)"
./reinstall.sh windows \
  --image-name "$IMAGE_NAME" \
  --iso "$ISO_URL" \
  --lang en-us \
  --username "$USERNAME" \
  --password "$RDP_PASS" \
  --rdp-port "$RDP_PORT" \
  --allow-ping \
  --no-lockout-threshold \
  --hold "$HOLD" 2>&1 | tee /root/install-stage1.log

rc=${PIPESTATUS[0]}
[ "$rc" = 0 ] || die "reinstall.sh exited $rc — see /root/install-stage1.log"

cat <<EOF

$(log "=== STAGE 1 COMPLETE ===")
Network captured : $IP/$PREFIX gw=$GW dns=$DNS1,$DNS2
Next             : reboot into the installer, wait for hold 2, then run stage 2.

  reboot

  # after the box answers SSH again (Alpine, credentials = the Windows ones):
  bash $(basename "$0") --after-hold

Do NOT hand-roll GRUB. trans.sh installs and configures it itself
(trans.sh:8593-8607). Re-running grub-install from Alpine breaks the MBR and
leaves a box that cannot boot or be reached.

EOF
