#!/bin/bash
# Dev Base Template
# Minimal development foundation with GUI support
#
# Includes:
#   - Build essentials (gcc, make, pkg-config)
#   - Git, curl, wget
#   - Wayland/Weston for GUI apps
#   - Common system libraries
#   - Claude Code ready (terminal + editor support)
#
# Usage: Called by dev.sh, not directly

set -e

TEMPLATE_NAME="dev-template"
MACHINE_PATH="/var/lib/machines/$TEMPLATE_NAME"

# Colors
CYAN='\033[0;36m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[OK]${NC} $1"; }
log_dev() { echo -e "${CYAN}[DEV]${NC} $1"; }

create_base_template() {
    log_dev "Creating dev base template..."

    if machinectl show-image "$TEMPLATE_NAME" &>/dev/null; then
        log_info "Template $TEMPLATE_NAME already exists"
        return 0
    fi

    # Bootstrap Debian trixie
    log_info "Bootstrapping Debian trixie..."
    sudo debootstrap --include=systemd,dbus trixie "$MACHINE_PATH" http://deb.debian.org/debian

    # Create nspawn config
    log_info "Configuring container..."
    sudo mkdir -p /etc/systemd/nspawn
    sudo tee /etc/systemd/nspawn/$TEMPLATE_NAME.nspawn > /dev/null << 'EOF'
[Exec]
Boot=yes
# Needed for Wayland socket access
PrivateUsers=no

[Network]
VirtualEthernet=no

[Files]
# Project directories bound at runtime by dev.sh
EOF

    # Start for configuration
    log_info "Starting template for configuration..."
    sudo machinectl start "$TEMPLATE_NAME"
    sleep 5

    # Fix DNS
    log_info "Configuring DNS..."
    sudo machinectl shell "$TEMPLATE_NAME" /bin/bash -c '
systemctl stop systemd-resolved 2>/dev/null || true
systemctl disable systemd-resolved 2>/dev/null || true
rm -f /etc/resolv.conf
echo "nameserver 8.8.8.8" > /etc/resolv.conf
echo "nameserver 1.1.1.1" >> /etc/resolv.conf
'

    # Add security and updates repos (debootstrap only sets up the base mirror)
    log_info "Adding security and updates repositories..."
    sudo machinectl shell "$TEMPLATE_NAME" /bin/bash -c '
cat >> /etc/apt/sources.list << SOURCES

# Security updates
deb https://security.debian.org/debian-security trixie-security main
# Point release updates
deb http://deb.debian.org/debian trixie-updates main
SOURCES
'

    # Install base packages
    log_info "Installing base development packages..."
    sudo machinectl shell "$TEMPLATE_NAME" /bin/bash -c '
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y \
    build-essential \
    pkg-config \
    cmake \
    git \
    curl \
    wget \
    ca-certificates \
    gnupg \
    lsb-release \
    sudo \
    vim \
    less \
    file \
    unzip \
    jq \
    htop \
    locales \
    man-db \
    bash-completion \
    openssh-client \
    unattended-upgrades \
    apt-listchanges

# Generate locale
sed -i "/en_US.UTF-8/s/^# //g" /etc/locale.gen
locale-gen

# Enable unattended security upgrades
cat > /etc/apt/apt.conf.d/20auto-upgrades << AUTOUPGRADE
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
AUTOUPGRADE
'

    # Install GUI/Wayland support
    log_info "Installing Wayland/GUI support..."
    sudo machinectl shell "$TEMPLATE_NAME" /bin/bash -c '
DEBIAN_FRONTEND=noninteractive apt-get install -y \
    weston \
    libegl1 \
    libgl1 \
    libgbm1 \
    libwayland-client0 \
    libwayland-cursor0 \
    libwayland-egl1 \
    libxkbcommon0 \
    fonts-noto \
    fonts-liberation \
    fonts-noto-color-emoji \
    fontconfig \
    dbus-x11 \
    xdg-utils \
    libpipewire-0.3-0 \
    pipewire-pulse
'

    # Install common native library deps (needed by many language ecosystems)
    log_info "Installing common native libraries..."
    sudo machinectl shell "$TEMPLATE_NAME" /bin/bash -c '
DEBIAN_FRONTEND=noninteractive apt-get install -y \
    libssl-dev \
    libffi-dev \
    zlib1g-dev \
    libbz2-dev \
    libreadline-dev \
    libsqlite3-dev \
    libncurses-dev \
    libxml2-dev \
    libxslt-dev \
    libyaml-dev \
    libcurl4-openssl-dev
'

    # Create dev user (uid 1000 to match host for file permissions)
    log_info "Creating dev user..."
    sudo machinectl shell "$TEMPLATE_NAME" /bin/bash -c '
useradd -m -u 1000 -s /bin/bash -G sudo dev || true
echo "dev ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/dev
chmod 440 /etc/sudoers.d/dev

# Setup XDG runtime dir
mkdir -p /run/user/1000
chmod 700 /run/user/1000
chown dev:dev /run/user/1000
echo "d /run/user/1000 0700 dev dev -" > /etc/tmpfiles.d/xdg-runtime.conf

# Create directories for common bind mounts
mkdir -p /home/dev/.ssh /home/dev/.claude /home/dev/.cache /home/dev/.config/git
chmod 700 /home/dev/.ssh
chown -R dev:dev /home/dev/.ssh /home/dev/.claude /home/dev/.cache /home/dev/.config

# Weston config for dev (cyan panel)
mkdir -p /home/dev/.config
cat > /home/dev/.config/weston.ini << '\''WESTON'\''
[core]
xwayland=false
idle-time=0

[shell]
panel-color=0xff00cccc
panel-position=top
background-color=0xff1a1a1a
clock-format=none
locking=false

[terminal]
font=monospace
font-size=11
WESTON

chown -R dev:dev /home/dev

# Bashrc additions
cat >> /home/dev/.bashrc << '\''BASHRC'\''

# Dev container environment
export XDG_RUNTIME_DIR=/run/user/1000
export WAYLAND_DISPLAY=wayland-0
export LANG=en_US.UTF-8
export EDITOR=vim

# Colored prompt showing container name
PS1="\[\033[0;36m\][dev]\[\033[0m\] \w \$ "
BASHRC
'

    # Stop template
    sudo machinectl stop "$TEMPLATE_NAME"

    log_success "Dev base template created: $TEMPLATE_NAME"
}

# Run if executed directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    create_base_template
fi
