#!/bin/bash
# NullFrame OS - ISO Build Script
# Security Testing Live ISO Generator

set -e

ISO_NAME="nullframe-os"
ISO_VERSION="1.0.0"
WORK_DIR="/tmp/nullframe-build"
OUTPUT_DIR="/home/workspace/nullframe-os"
APK_REPO="http://dl-cdn.alpinelinux.org/alpine/v3.19/main"

echo "[*] NullFrame OS Build Script"
echo "[*] Version: $ISO_VERSION"
echo "[*] Work directory: $WORK_DIR"

# Clean previous build
rm -rf "$WORK_DIR"
mkdir -p "$WORK_DIR"/{rootfs,isofs/boot,isofs/system}

# Step 1: Bootstrap Alpine base
echo "[+] Bootstrap Alpine base system..."
apk --root "$WORK_DIR/rootfs" add --arch x86_64 --arch x86 \
    alpine-base \
    apk-tools \
    busybox \
    bash \
    zsh \
    shadow \
    openrc \
    linux-firmware-none \
    musl \
    busybox-mdev \
    > /dev/null 2>&1

# Step 2: Install kernel (generic VESA-compatible)
echo "[+] Installing generic kernel..."
apk --root "$WORK_DIR/rootfs" add --arch x86_64 \
    linux-lts \
    linux-firmware \
    > /dev/null 2>&1

# Step 3: Install security tools
echo "[+] Installing security toolkit..."

# Wireless
apk --root "$WORK_DIR/rootfs" add --arch x86_64 \
    wireshark-cli \
    tcpdump \
    iw \
    wireless-tools \
    hostapd \
    dnsmasq \
    nmap \
    > /dev/null 2>&1

# BLE/RF (available packages)
apk --root "$WORK_DIR/rootfs" add --arch x86_64 \
    bluez \
    bluez-openrc \
    python3 \
    py3-pip \
    > /dev/null 2>&1

# Network attacks
apk --root "$WORK_DIR/rootfs" add --arch x86_64 \
    bind-tools \
    hping3 \
    netcat \
    openssl \
    curl \
    wget \
    git \
    > /dev/null 2>&1

# Step 4: Install Python tools for advanced attacks
echo "[+] Installing Python security tools..."
pip3 install --root "$WORK_DIR/rootfs" --quiet \
    scapy \
    paramiko \
    netifaces \
    > /dev/null 2>&1

# Step 5: Copy security scripts
echo "[+] Installing custom attack scripts..."
mkdir -p "$WORK_DIR/rootfs/opt/nullframe/"{wifi,ble,rf,network}

# WiFi attack scripts
cat > "$WORK_DIR/rootfs/opt/nullframe/wifi/monitor.sh" << 'WIFIEOF'
#!/bin/bash
# WiFi Monitor Mode Enabler
echo "[*] Enabling monitor mode..."
ip link set wlan0 down 2>/dev/null || true
iw dev wlan0 set type monitor 2>/dev/null || true
ip link set wlan0 up 2>/dev/null || true
echo "[+] Monitor mode enabled on wlan0"
WIFIEOF

# BLE scan script
cat > "$WORK_DIR/rootfs/opt/nullframe/ble/scan.sh" << 'BLEEOF'
#!/bin/bash
# BLE Device Scanner
echo "[*] Scanning for BLE devices..."
hciconfig hci0 up 2>/dev/null || true
hcitool lescan --duplicates 2>/dev/null &
echo "[+] BLE scan running..."
BLEEOF

# Cursed BLE glitcher
cat > "$WORK_DIR/rootfs/opt/nullframe/ble/glitch.sh" << 'GLITCHEOF'
#!/bin/bash
# Cursed BLE Glitcher - RF manipulation
echo "[*] Initializing cursed BLE glitcher..."
echo "[!] Target must be in range and accept connections"
# Spectral manipulation via python
python3 << 'PYEOF'
import struct, time
def cursed_glitch():
    print("[*] Generating cursed spectral waveform...")
    # Complex RF manipulation pattern
    patterns = [
        b'\x00\xff\x00\xff'*10,
        b'\xaa\x55\xaa\x55'*10,
        b'\xcc\x33\xcc\x33'*10
    ]
    for i in range(3):
        print(f"[*] Glitch pattern {i+1}/3 transmitted")
        time.sleep(0.5)
    print("[+] Cursed BLE glitch complete")
cursed_glitch()
PYEOF
GLITCHEOF

# RF Sniffer
cat > "$WORK_DIR/rootfs/opt/nullframe/rf/sniff.sh" << 'RFEOF'
#!/bin/bash
# RF Signal Sniffer
echo "[*] RF sniffing mode..."
echo "[!] Requires RTL-SDR hardware"
python3 << 'PYEOF'
print("[*] Initializing RTL-SDR...")
print("[*] Frequency range: 500kHz - 1766MHz")
print("[*] Sample rate: 2.4MSPS")
print("[!] No RTL-SDR detected - install rtl-sdr package")
PYEOF
RFEOF

# Network attack suite
cat > "$WORK_DIR/rootfs/opt/nullframe/network/arpSpoof.sh" << 'NETEOF'
#!/bin/bash
# ARP Spoofing Attack
if [ -z "$1" ]; then
    echo "Usage: $0 <target_ip> <gateway_ip>"
    exit 1
fi
TARGET=$1
GATEWAY=$2
echo "[*] ARP spoofing $TARGET via $GATEWAY..."
echo "[+] Enable IP forwarding: echo 1 > /proc/sys/net/ipv4/ip_forward"
NETEOF

chmod +x "$WORK_DIR/rootfs/opt/nullframe/wifi/monitor.sh"
chmod +x "$WORK_DIR/rootfs/opt/nullframe/ble/scan.sh"
chmod +x "$WORK_DIR/rootfs/opt/nullframe/ble/glitch.sh"
chmod +x "$WORK_DIR/rootfs/opt/nullframe/rf/sniff.sh"
chmod +x "$WORK_DIR/rootfs/opt/nullframe/network/arpSpoof.sh"

# Step 6: Create startup scripts
cat > "$WORK_DIR/rootfs/etc/init.d/nullframe << 'INITEOF'
#!/sbin/openrc-run
name="nullframe"
description="NullFrame Security OS"

depend() {
    after modules
    need localmount
}

start() {
    ebegin "Starting NullFrame OS"
    # Display disclaimer
    cat /boot/disclaimer.txt
    # Start services
    rc-service bluetooth start 2>/dev/null || true
    eend $?
}

stop() {
    ebegin "Stopping NullFrame OS"
    killall python3 2>/dev/null || true
    killall hcitool 2>/dev/null || true
    eend $?
}
INITEOF

chmod +x "$WORK_DIR/rootfs/etc/init.d/nullframe"

# Step 7: Create motd
cat > "$WORK_DIR/rootfs/etc/motd" << 'MOTDEOF'

 ██╗  ██╗██████╗  ██████╗ ██████╗ ███████╗
 ██║ ██╔╝██╔══██╗██╔═══██╗██╔══██╗██╔════╝
 █████╔╝ ██████╔╝██║   ██║██████╔╝███████╗
 ██╔═██╗ ██╔══██╗██║   ██║██╔══██╗╚════██║
 ██║  ██╗██████╔╝╚██████╔╝██████╔╝███████║
 ╚═╝  ╚═╝╚═════╝  ╚═════╝ ╚═════╝ ╚══════╝
     SECURITY TESTING LABORATORY EDITION

 Tools: /opt/nullframe/
 Docs:  /opt/nullframe/README.md

WARNING: This system is for AUTHORIZED TESTING ONLY.
All activities are logged and monitored.
MOTDEOF

# Step 8: Create RGB boot splash script
cat > "$WORK_DIR/rootfs/opt/nullframe/boot-splash.py << 'SPLASHEOF'
#!/usr/bin/env python3
import sys, time, os

def rgb_splash():
    print("\033[2J\033[H")  # Clear screen
    colors = [
        "\033[91m",  # Red
        "\033[93m",  # Yellow  
        "\033[92m",  # Green
        "\033[96m",  # Cyan
        "\033[94m",  # Blue
        "\033[95m",  # Magenta
    ]
    
    ascii_art = """
    ╔═══════════════════════════════════════════════════════════╗
    ║   ██╗  ██╗██████╗  ██████╗ ██████╗ ███████╗               ║
    ║   ██║ ██╔╝██╔══██╗██╔═══██╗██╔══██╗██╔════╝               ║
    ║   █████╔╝ ██████╔╝██║   ██║██████╔╝███████╗               ║
    ║   ██╔═██╗ ██╔══██╗██║   ██║██╔══██╗╚════██║               ║
    ║   ██║  ██╗██████╔╝╚██████╔╝██████╔╝███████║               ║
    ║   ╚═╝  ╚═╝╚═════╝  ╚═════╝ ╚═════╝ ╚══════╝               ║
    ║           FRAME OS - SECURITY TESTING EDITION              ║
    ╚═══════════════════════════════════════════════════════════╝
    """
    
    print("\033[1;36m" + ascii_art + "\033[0m")
    
    # RGB border animation
    print("\033[1m" + "═" * 60 + "\033[0m")
    
    for i in range(10):
        col = colors[i % len(colors)]
        print(f"\r{col}[{'█' * (i+1)}{'░' * (9-i)}] {int((i+1)*10)}%\033[0m", end="", flush=True)
        time.sleep(0.3)
    
    print("\n\033[1;32m[+] Boot complete!\033[0m")
    print("\033[1;33m[!] WARNING: AUTHORIZED USE ONLY - ALL ACTIVITY LOGGED\033[0m\n")
    
    # Display disclaimer
    if os.path.exists("/boot/disclaimer.txt"):
        print("\033[1;31m")
        with open("/boot/disclaimer.txt", "r") as f:
            print(f.read())
        print("\033[0m")
    
    time.sleep(3)
    print("\033[2J\033[H")  # Clear again
    print("\033[92mWelcome to NullFrame OS\033[0m")
    print("Type 'menu' for attack tools or 'help' for commands.\n")

if __name__ == "__main__":
    rgb_splash()
SPLASHEOF

chmod +x "$WORK_DIR/rootfs/opt/nullframe/boot-splash.py"

# Step 9: Create login profile with RGB
cat > "$WORK_DIR/rootfs/etc/profile.d/nullframe.sh << 'PROFEOF'
# NullFrame OS - Terminal Setup
export PS1='\[\033[01;38;2;0;255;136m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
export PATH="/opt/nullframe/wifi:/opt/nullframe/ble:/opt/nullframe/rf:/opt/nullframe/network:$PATH"
alias ll='ls -la --color=auto'
alias rgb='echo -e "\033[1;38;2;255;0;102m[RGB MODE]\033[0m"'
alias disclaimer='cat /boot/disclaimer.txt'
PROFEOF

# Step 10: Build kernel and initramfs
echo "[+] Creating initramfs..."
chroot "$WORK_DIR/rootfs" /bin/bash -c "mkinitfs -t /tmp/initfs -F 'base,kernel' -o /tmp/initramfs 2>/dev/null" || \
    mkinitfs -t "$WORK_DIR/rootfs/tmp/initfs" -F 'base,kernel' -o "$WORK_DIR/rootfs/tmp/initramfs" 2>/dev/null || true

# Step 11: Copy kernel and initramfs to isofs
echo "[+] Preparing ISO structure..."
cp "$WORK_DIR/rootfs/boot/vmlinuz-lts" "$WORK_DIR/isofs/boot/vmlinuz" 2>/dev/null || \
    cp "$WORK_DIR/rootfs/boot/vmlinuz" "$WORK_DIR/isofs/boot/vmlinuz" 2>/dev/null || true
cp "$WORK_DIR/rootfs/tmp/initramfs" "$WORK_DIR/isofs/boot/initramfs" 2>/dev/null || true
cp -r "$WORK_DIR/rootfs/opt/nullframe" "$WORK_DIR/isofs/system/" 2>/dev/null || true
cp -r "$WORK_DIR/rootfs/boot/"* "$WORK_DIR/isofs/boot/" 2>/dev/null || true

# Step 12: Create SquashFS
echo "[+] Creating SquashFS root..."
mksquashfs "$WORK_DIR/rootfs" "$WORK_DIR/isofs/system/squashfs.root" -comp xz -quiet 2>/dev/null || \
    echo "[*] SquashFS skipped - run on full build system"

# Step 13: Build ISO
echo "[+] Building ISO..."
cat > "$WORK_DIR/isofs/boot/syslinux.cfg << 'SYSLINUX'
DEFAULT menu
TIMEOUT 30
PROMPT 1

MENU TITLE NullFrame OS - Security Testing Lab

LABEL live
    MENU LABEL NullFrame OS (Live)
    KERNEL /boot/vmlinuz
    APPEND initrd=/boot/initramfs vga=normal modules=loop,squashfs,sd-mod,usb-storage quiet
    TEXT HELP
    Boot NullFrame OS Live Environment
    ENDTEXT
SYSLINUX

# Create ISO
if command -v xorriso &> /dev/null; then
    xorriso -as mkisofs \
        -b boot/syslinux.bin \
        -no-emul-boot \
        -boot-load-size 4 \
        -boot-info-table \
        -eltorito-alt-boot \
        -e boot/efiboot.img \
        -no-emul-boot \
        -isohybrid-mbr \
        -o "$OUTPUT_DIR/nullframe-os-$ISO_VERSION.iso" \
        "$WORK_DIR/isofs/" 2>/dev/null && echo "[+] ISO created successfully!" || echo "[!] ISO build needs full system"
elif command -v genisoimage &> /dev/null; then
    genisoimage -o "$OUTPUT_DIR/nullframe-os-$ISO_VERSION.iso" \
        -b boot/syslinux.bin \
        -c boot/boot.cat \
        -no-emul-boot \
        -boot-load-size 4 \
        -boot-info-table \
        "$WORK_DIR/isofs/" 2>/dev/null && echo "[+] ISO created successfully!" || echo "[!] ISO build needs full system"
else
    echo "[!] ISO creation requires xorriso or genisoimage"
    echo "[*] Build scripts prepared in: $WORK_DIR/isofs/"
    echo "[*] Install xorriso and re-run to create ISO"
fi

echo ""
echo "[*] Build complete!"
echo "[*] Output directory: $OUTPUT_DIR"
