#!/bin/sh
# Build a Qiling x86-64 Windows rootfs from a mounted Windows installation.
#
#   ./qiling_rootfs.sh /run/media/you/Windows ~/qiling/rootfs/x8664_windows
#
# Copies the DLLs Qiling's PE loader needs plus the registry hives it
# opens at startup. Reads the Windows volume; writes only to the rootfs.
set -eu

WIN="${1:?usage: qiling_rootfs.sh <mounted-windows-root> <rootfs-dir>}"
OUT="${2:?usage: qiling_rootfs.sh <mounted-windows-root> <rootfs-dir>}"

SYS32="$WIN/Windows/System32"
CONF="$SYS32/config"

[ -d "$SYS32" ] || { echo "no System32 under $WIN" >&2; exit 1; }

mkdir -p "$OUT/Windows/System32" "$OUT/Windows/registry"

# Paths a sample writes to must already exist -- Qiling's CreateFile does not
# create parent directories, it just returns INVALID_HANDLE_VALUE.
mkdir -p "$OUT/Users/Public" "$OUT/Windows/Temp" "$OUT/ProgramData"

# Windows stores these with mixed case (KernelBase.dll, IPHLPAPI.DLL). Look
# them up case-insensitively and write them out lowercase, which is the form
# Qiling's loader asks for first.
for want in ntdll kernel32 kernelbase user32 advapi32 msvcrt ucrtbase \
            ws2_32 dnsapi mswsock iphlpapi urlmon wininet vcruntime140 \
            gdi32 shell32 shlwapi ole32 oleaut32 crypt32 bcrypt \
            sechost rpcrt4 psapi version; do
    src=$(find "$SYS32" -maxdepth 1 -iname "$want.dll" -print -quit)
    if [ -n "$src" ]; then
        cp "$src" "$OUT/Windows/System32/$want.dll"
    else
        echo "not found, skipping: $want.dll" >&2
    fi
done

# Qiling maps hive names onto files in Windows/registry. Four come straight
# from System32\config; HKCU comes from a user profile's NTUSER.DAT, and
# DEFAULT serves when you do not want a real user's hive in the rootfs.
for h in SAM SECURITY SOFTWARE SYSTEM; do
    cp "$CONF/$h" "$OUT/Windows/registry/$h"
done
cp "$CONF/DEFAULT" "$OUT/Windows/registry/NTUSER.DAT"

# HKLM\HARDWARE is volatile -- the kernel builds it in RAM at every boot, so
# there is no file to copy. Qiling opens it eagerly regardless, so give it
# the smallest valid hive as a stand-in.
cp "$CONF/SECURITY" "$OUT/Windows/registry/HARDWARE"

chmod -R u+w "$OUT"
printf '%s: %s DLLs, %s hives\n' "$OUT" \
    "$(ls "$OUT/Windows/System32" | wc -l)" \
    "$(ls "$OUT/Windows/registry" | wc -l)"
