#!/usr/bin/env bash

if [ "$#" -lt 3 ]; then
  echo "Usage: $0 <team_count> <wg_config_base_dir> <service1_dir> <service2_dir>..."
  exit 1
else
  TEAM_COUNT=$1
  WG_CONFIG_BASE_DIR=$2
  shift 2
  SERVICE_DIRS=("$@")
fi

if ls vulnbox*.qcow2 1> /dev/null 2>&1; then
  read -p "Vulnbox QCOW2 files found in current directory. Remove them? (y/n) " choice
  rm -rf vulnbox*.qcow2
fi

bash create_service_zip.sh "${SERVICE_DIRS[@]}"

INPUT_FILE="debian-13-nocloud-amd64.qcow2"
if [ -f "$INPUT_FILE" ]; then
  echo "Base image $INPUT_FILE already exists. Skipping download."
else
  echo "Base image $INPUT_FILE not found. Downloading..."
  wget https://cloud.debian.org/images/cloud/trixie/latest/debian-13-nocloud-amd64.qcow2 -O $INPUT_FILE
  if [ $? -ne 0 ]; then
    echo "Error downloading base image. Exiting."
    exit 1
  fi
fi

qemu-img convert -f qcow2 -O qcow2 $INPUT_FILE vulnbox_base.qcow2
qemu-img create -f qcow2 -o preallocation=metadata,size=20G vulnbox_resized.qcow2
virt-resize --expand /dev/sda1 vulnbox_base.qcow2 vulnbox_resized.qcow2
mv vulnbox_resized.qcow2 vulnbox_base.qcow2

# Copy encrypted service tarball and install, enable sshd root password and uncomment it
virt-customize -a vulnbox_base.qcow2 \
  --upload ./services.zip:/root/services.zip \
  --install qemu-guest-agent,wireguard,iproute2,docker.io,openssh-server,ncat,zip,unzip,docker-compose,vim,nano,tmux \
  --run-command 'sed -i "s/.*PermitRootLogin.*/PermitRootLogin yes/" /etc/ssh/sshd_config' \
  --run-command 'sed -i "s/.*PasswordAuthentication.*/PasswordAuthentication yes/" /etc/ssh/sshd_config' \
  --run-command 'systemctl enable qemu-guest-agent' \
  --run-command 'systemctl enable docker'


function generate_vulnbox(){
  local team_name=$1
  local password=$2
  local wg_peer_config=$3
  echo "Generating vulnbox for team: ${team_name}"
  echo "Password: ${password}"
  echo "${password}" > vulnbox_${team_name}_password.txt
  cp vulnbox_base.qcow2 vulnbox_${team_name}.qcow2

  local vulnbox_file=vulnbox_${team_name}.qcow2
  virt-customize -a $vulnbox_file \
    --upload "$wg_peer_config":/etc/wireguard/peer.conf \
    --run-command "echo 'root:$password' | chpasswd" \
    --run-command 'systemctl enable wg-quick@peer'

}

TEAM_NAME="nop"
PASSWORD="$(openssl rand -base64 12)"

# Generate WireGuard peer configuration for this team
WG_PEER_CONFIG="${WG_CONFIG_BASE_DIR}/nop_vulnbox.conf"

generate_vulnbox "$TEAM_NAME" "$PASSWORD" "$WG_PEER_CONFIG"

for i in $(seq 1 $TEAM_COUNT); do
  TEAM_NAME="team$i"
  PASSWORD="$(openssl rand -base64 12)"

  # Generate WireGuard peer configuration for this team
  WG_PEER_CONFIG="${WG_CONFIG_BASE_DIR}/$i/vulnbox.conf"

  generate_vulnbox "$TEAM_NAME" "$PASSWORD" "$WG_PEER_CONFIG"
done


# Cleanup
rm -f vulnbox_base.qcow2

echo 'qemu-system-x86_64 \
  -enable-kvm \
  -m 4096 -smp 4 -cpu host \
  -drive file=<file>,if=virtio,cache=writeback,format=qcow2 \
  -netdev user,id=net0\
  -device virtio-net-pci,netdev=net0 \
  -nographic'

