#!/bin/sh
# PXE Server Automated Setup Script for Alpine Linux
# This script should be run inside the Alpine installer environment
# Usage: sh pxe-server-setup.sh

set -e

echo "=== UltraCloud PXE Server Setup ==="
echo "This script will:"
echo "1. Install Alpine Linux to disk"
echo "2. Configure static networking (192.168.100.1)"
echo "3. Install and configure dnsmasq (DHCP/DNS/TFTP)"
echo "4. Install openssh for remote access"
echo ""

# 1. Configure keyboard and hostname
setup-keymap us us
setup-hostname pxe-server

# 2. Configure network interfaces
cat > /tmp/interfaces <<'EOF'
auto lo
iface lo inet loopback

# Multicast network (cluster nodes)
auto eth0
iface eth0 inet static
    address 192.168.100.1
    netmask 255.255.255.0

# User network (internet access)
auto eth1
iface eth1 inet dhcp
EOF

cp /tmp/interfaces /etc/network/interfaces
rc-service networking restart

# 3. Configure DNS (use public DNS for outbound)
echo "nameserver 8.8.8.8" > /etc/resolv.conf
echo "nameserver 8.8.4.4" >> /etc/resolv.conf

# 4. Setup APK repositories (use fastest mirror)
setup-apkrepos -f

# 5. Install system to disk
echo "Installing Alpine to disk /dev/vda..."
echo -e "y\n" | setup-disk -m sys /dev/vda

# 6. Mount the new root and configure it
mount /dev/vda3 /mnt
mount /dev/vda1 /mnt/boot

# 7. Install required packages in the new system
chroot /mnt apk add --no-cache \
    dnsmasq \
    openssh \
    curl \
    bash \
    vim

# 8. Configure dnsmasq in the new system
cat > /mnt/etc/dnsmasq.conf <<'EOF'
# UltraCloud PXE Server dnsmasq configuration

# Interface to listen on (multicast network)
interface=eth0

# DHCP range for cluster nodes
dhcp-range=192.168.100.100,192.168.100.150,12h

# DHCP options
dhcp-option=3,192.168.100.1   # Gateway
dhcp-option=6,192.168.100.1   # DNS server

# Static DHCP leases for nodes
dhcp-host=52:54:00:00:01:01,node01,192.168.100.11
dhcp-host=52:54:00:00:01:02,node02,192.168.100.12
dhcp-host=52:54:00:00:01:03,node03,192.168.100.13

# DNS domain
domain=plasma.local
local=/plasma.local/

# Enable TFTP
enable-tftp
tftp-root=/var/lib/tftpboot

# Logging
log-queries
log-dhcp

# PXE boot configuration (optional - for future PXE boot testing)
# dhcp-boot=pxelinux.0
EOF

# 9. Create TFTP boot directory
mkdir -p /mnt/var/lib/tftpboot

# 10. Copy network configuration to new system
cp /tmp/interfaces /mnt/etc/network/interfaces

# 11. Configure SSH
echo "PermitRootLogin yes" >> /mnt/etc/ssh/sshd_config

# 12. Enable services in new system
chroot /mnt rc-update add networking boot
chroot /mnt rc-update add dnsmasq default
chroot /mnt rc-update add sshd default

# 13. Set root password (for SSH access)
echo "root:ultracloud" | chroot /mnt chpasswd

echo ""
echo "=== Installation Complete ==="
echo "System will reboot from disk"
echo "PXE server will be available at: 192.168.100.1"
echo "DHCP range: 192.168.100.100-150"
echo "SSH: ssh root@192.168.100.1 (password: ultracloud)"
echo ""
echo "Press Enter to reboot..."
read
reboot
