#!/bin/bash
set -e

# Start libvirt and virtlogd services
echo "Starting libvirt and virtlogd daemons..."
/usr/sbin/libvirtd -d
/usr/sbin/virtlogd -d
sleep 2 # Give daemons a moment to start

# Change to the Vagrant project directory
cd /opt/win10 || exit

# Bring up the VM. This command is idempotent.
echo "Bringing up the VM..."
vagrant up

# Get the VM IP address using virsh
echo "Fetching VM IP address..."
DOMAIN_NAME="win10_default"

# It can take a while for the guest agent to report the IP address.
# We will retry a few times.
VM_IP=""
for i in {1..12}; do # Retry for 2 minutes (12 * 10s)
    # The output of domifaddr can be multiline, we are interested in ipv4
    # The output looks like:
    # Name       MAC address          Protocol     Address
    # -------------------------------------------------------------------------------
    # vnet1      52:54:00:ab:cd:ef    ipv4         192.168.121.44/24
    VM_IP=$(virsh domifaddr "$DOMAIN_NAME" 2>/dev/null | grep ipv4 | awk '{print $4}' | cut -d'/' -f1)
    if [ -n "$VM_IP" ]; then
        echo "VM IP Address found: $VM_IP"
        break
    fi
    echo "Waiting for VM to get an IP address... (attempt $i/12)"
    sleep 10
done

if [ -z "$VM_IP" ]; then
    echo "Fatal: Failed to get VM IP address after multiple retries."
    exit 1
fi

echo "Windows VM IP Address: $VM_IP"

# Enable IP forwarding and configure NAT
echo "Enabling IP forwarding and NAT for RDP..."
sysctl -w net.ipv4.ip_forward=1

# iptables에 필요한 커널 모듈 로드
echo "Loading required kernel modules for iptables..."
modprobe ip_tables
modprobe iptable_nat
modprobe nf_nat
modprobe xt_conntrack

iptables -t nat -A PREROUTING -p tcp --dport 3389 -j DNAT --to-destination "$VM_IP":3389
iptables -t nat -A POSTROUTING -j MASQUERADE

iptables -t nat -A PREROUTING -p tcp --dport 8090 -j DNAT --to-destination "$VM_IP":8090
iptables -t nat -A POSTROUTING -j MASQUERADE

# Configure RDP forwarding inside the container
echo "Allowing RDP forwarding to the VM..."
iptables -I FORWARD -d "$VM_IP" -p tcp --dport 3389 -j ACCEPT
iptables -I FORWARD -s "$VM_IP" -j ACCEPT

iptables -I FORWARD -d "$VM_IP" -p tcp --dport 8090 -j ACCEPT
iptables -I FORWARD -s "$VM_IP" -j ACCEPT

# Keep the container running to maintain the VM session
echo "Windows VM is running. You can connect via RDP at $VM_IP."

# Keep the container running
echo "Container is running. Use 'docker exec' to access it."
tail -f /dev/null
