#!/bin/bash
# Setup script for apt-cacher-ng to speed up package downloads

set -e

echo "Setting up apt-cacher-ng for faster builds..."

# Check if apt-cacher-ng is installed
if ! command -v apt-cacher-ng &> /dev/null; then
    echo "Installing apt-cacher-ng..."
    sudo apt-get update
    sudo apt-get install -y apt-cacher-ng
fi

# Start and enable apt-cacher-ng service
echo "Starting apt-cacher-ng service..."
sudo systemctl enable apt-cacher-ng
sudo systemctl start apt-cacher-ng

# Get the proxy address
PROXY_ADDR=$(ip route get 1 | awk '{print $7; exit}')
PROXY_PORT="3142"
PROXY_URL="http://${PROXY_ADDR}:${PROXY_PORT}"

echo "Apt-cacher-ng is running at: ${PROXY_URL}"
echo "You can access the web interface at: http://${PROXY_ADDR}:3142/acng-report.html"

# Create a configuration file for the project
mkdir -p config
cat > config/apt-cacher.conf << EOF
# Apt-cacher-ng configuration for Debian Atomic Desktop project
PROXY_URL=${PROXY_URL}
PROXY_ADDR=${PROXY_ADDR}
PROXY_PORT=${PROXY_PORT}

# Usage instructions:
# 1. In 02-installer/justfile, uncomment and set:
#    APT_CACHER_NG_PROXY := "${PROXY_URL}"
# 2. In Containerfiles, add:
#    RUN echo "Acquire::http::Proxy \"${PROXY_URL}\";" > /etc/apt/apt.conf.d/99proxy
EOF

echo "Configuration saved to config/apt-cacher.conf"
echo ""
echo "To use apt-cacher-ng in your builds:"
echo "1. Edit 02-installer/justfile and uncomment APT_CACHER_NG_PROXY"
echo "2. Set it to: ${PROXY_URL}"
echo "3. For container builds, add the proxy configuration to your Containerfile" 