#!/bin/bash -e
# Install Dangerous Pi backend and dependencies

echo "Installing Dangerous Pi..."

# Detect the default user (cloud-init compatible)
# Find first user with UID >= 1000 (excluding nobody)
DEFAULT_USER=$(awk -F: '$3 >= 1000 && $3 < 65534 {print $1; exit}' /etc/passwd)
if [ -z "$DEFAULT_USER" ]; then
    DEFAULT_USER="pi"  # Fallback to pi if detection fails
fi
DEFAULT_HOME=$(eval echo ~$DEFAULT_USER)

echo "Detected default user: $DEFAULT_USER (home: $DEFAULT_HOME)"

# Packages (nodejs, npm, lrzsz) installed by 00-apt-setup stage
# pip3 is available from stage2 Python installation

# Install Python packages from requirements.txt
pip3 install --break-system-packages -r /tmp/dangerous-pi-files/requirements.txt

# Create installation directory
mkdir -p /opt/dangerous-pi
cd /opt/dangerous-pi

# Copy application files (from temp directory prepared by 00-run.sh)
cp -r /tmp/dangerous-pi-files/* /opt/dangerous-pi/

# Create data and logs directories
mkdir -p /opt/dangerous-pi/data
mkdir -p /opt/dangerous-pi/logs

# Set ownership and permissions
chown -R $DEFAULT_USER:$DEFAULT_USER /opt/dangerous-pi
chmod +x /opt/dangerous-pi/scripts/*.sh
chmod +x /opt/dangerous-pi/systemd/*.sh

# Create environment file from template
cp /opt/dangerous-pi/systemd/dangerous-pi.env.example /opt/dangerous-pi/.env
chown $DEFAULT_USER:$DEFAULT_USER /opt/dangerous-pi/.env
chmod 600 /opt/dangerous-pi/.env

# Install backend systemd service (with user substitution for cloud-init compatibility)
sed "s/__DANGEROUS_PI_USER__/$DEFAULT_USER/g" /opt/dangerous-pi/systemd/dangerous-pi.service > /etc/systemd/system/dangerous-pi.service
chmod 644 /etc/systemd/system/dangerous-pi.service

# Install polkit rules for sudo-free network management
if [ -d /tmp/dangerous-pi-files/etc/polkit-1 ]; then
    mkdir -p /etc/polkit-1/rules.d
    sed "s/__DANGEROUS_PI_USER__/$DEFAULT_USER/g" /tmp/dangerous-pi-files/etc/polkit-1/rules.d/50-dangerous-pi.rules > /etc/polkit-1/rules.d/50-dangerous-pi.rules
    chmod 644 /etc/polkit-1/rules.d/50-dangerous-pi.rules
    echo "Installed polkit rules for $DEFAULT_USER"
fi

# Add user to netdev group for network management
usermod -a -G netdev $DEFAULT_USER

# Frontend setup (Remix SSR)
# build_frontend() in build-image.sh pre-builds on the host.
# All production deps are pure JS (no native modules), so the host
# node_modules works on arm64 without reinstalling.
cd /opt/dangerous-pi/app/frontend
if [ -d "build/server" ]; then
    echo "Using pre-built frontend from host..."
    # Remove build-time-only packages to save ~100MB of image space
    rm -rf node_modules/.cache \
           node_modules/@rollup \
           node_modules/@esbuild \
           node_modules/@remix-run/dev \
           node_modules/vite \
           node_modules/typescript \
           node_modules/@types
else
    echo "Building frontend in chroot (no pre-built output found)..."
    npm install --production=false
    npm run build
    rm -rf node_modules/.cache
    npm prune --production
fi
cd /opt/dangerous-pi

# Install frontend systemd service
cat > /etc/systemd/system/dangerous-pi-frontend.service << EOF
[Unit]
Description=Dangerous Pi Frontend Service
Documentation=https://github.com/grizmin/dangerous-pi
After=network.target dangerous-pi.service
Wants=dangerous-pi.service

[Service]
Type=simple
User=$DEFAULT_USER
Group=$DEFAULT_USER
WorkingDirectory=/opt/dangerous-pi/app/frontend
Environment="NODE_ENV=production"
Environment="PORT=3000"
ExecStart=/usr/bin/node node_modules/@remix-run/serve/dist/cli.js build/server/index.js

# Restart policy
Restart=always
RestartSec=5
StartLimitBurst=5
StartLimitInterval=60

# Resource limits (lighter than backend)
MemoryMax=256M
CPUQuota=50%

# Graceful shutdown
TimeoutStopSec=10
KillMode=mixed
KillSignal=SIGTERM

[Install]
WantedBy=multi-user.target
EOF
chmod 644 /etc/systemd/system/dangerous-pi-frontend.service

# Add default user to required hardware groups
usermod -a -G i2c,bluetooth,gpio,dialout $DEFAULT_USER

# Enable I2C interface (for UPS HAT)
# Try both possible boot config locations (legacy and modern Pi OS)
BOOT_CONFIG="/boot/firmware/config.txt"
if [ ! -f "$BOOT_CONFIG" ]; then
    BOOT_CONFIG="/boot/config.txt"
fi

if [ -f "$BOOT_CONFIG" ]; then
    if ! grep -q "^dtparam=i2c_arm=on" "$BOOT_CONFIG"; then
        echo "dtparam=i2c_arm=on" >> "$BOOT_CONFIG"
    fi
else
    echo "WARNING: Boot config not found at /boot/config.txt or /boot/firmware/config.txt"
fi

# Ensure i2c-dev module loads at boot (required for /dev/i2c-* devices)
echo "Configuring i2c-dev module to load at boot..."
mkdir -p /etc/modules-load.d
echo "i2c-dev" > /etc/modules-load.d/i2c-dev.conf

# Enable services to start on boot
systemctl enable dangerous-pi.service
systemctl enable dangerous-pi-frontend.service

# Clean up package manager cache (saves ~50MB)
apt-get clean
apt-get autoclean
apt-get autoremove -y

# Clean pip cache
pip3 cache purge 2>/dev/null || true

# Clean npm cache
npm cache clean --force 2>/dev/null || true

echo "Dangerous Pi installation complete!"
echo "Frontend: http://dangerous-pi.local (via nginx)"
echo "Backend API: http://dangerous-pi.local/api/"
