#!/bin/bash
set -e

# Route outbound traffic via real-internet bridge
ip route del default 2>/dev/null || true
ip route add default via 172.30.0.1

rm -f /run/squid.pid

# Initialize the cache swap directories before starting Squid. The image's
# build-time `squid -z` can leave an INCOMPLETE L1/L2 set (observed: 00–0C
# present, 0D–0F missing); on a fresh container Squid then FATALs with "Failed
# to verify one of the swap directories" and exits. With Squid dead, the
# transparent-proxy REDIRECT (:80→3128, :443→3129) forwards every apt fetch to
# a closed port → "connection refused" — which surfaced as flaky, non-warming
# `apt install` failures during module deploys (e.g. knot). `squid -z` is
# idempotent (creates only missing dirs). `--foreground` is REQUIRED: a bare
# `squid -z` daemonizes and lingers (holding /run/squid.pid), so the following
# `squid -N` would FATAL "Squid is already running"; with --foreground, -z runs
# synchronously, removes the pid file, and exits clean.
squid --foreground -z -f /etc/squid/squid.conf
rm -f /run/squid.pid

echo "forward-proxy ready on ports 3128 (HTTP) / 3129 (HTTPS)"
exec squid -N -f /etc/squid/squid.conf
