#!/data/data/com.termux/files/usr/bin/bash
# 80bee Pi-hole automated setup script
# Designed to be launched via Termux RunCommandService

echo "[80bee] Initializing Termux Environment..."
# Force a highly stable mirror (Grimler.se) to bypass common MWT sync issues
echo "deb https://grimler.se/termux/termux-main stable main" > /data/data/com.termux/files/usr/etc/apt/sources.list

echo "[80bee] Upgrading core Termux packages (Fixing broken curl/openssl)..."
export DEBIAN_FRONTEND=noninteractive
apt update -y && apt full-upgrade -y -o Dpkg::Options::="--force-confnew" || {
    echo "[80bee] Grimler mirror failed. Trying Cloudflare fallback..."
    echo "deb https://packages.termux.dev/apt/termux-main stable main" > /data/data/com.termux/files/usr/etc/apt/sources.list
    apt update -y && apt full-upgrade -y -o Dpkg::Options::="--force-confnew"
}

echo "[80bee] Installing required packages..."
pkg install proot-distro wget curl inetutils -y

if ! command -v proot-distro >/dev/null 2>&1; then
    echo "[80bee] ERROR: proot-distro failed to install! Check network/mirrors. Aborting."
    exit 1
fi

UBUNTU_ROOTFS="/data/data/com.termux/files/usr/var/lib/proot-distro/installed-rootfs/ubuntu"

# Clear out any corrupted rootfs from previous interrupted runs
if [ -d "$UBUNTU_ROOTFS" ] && [ ! -d "$UBUNTU_ROOTFS/etc" ]; then
    echo "[80bee] Found corrupted Ubuntu container. Cleaning up..."
    rm -rf "$UBUNTU_ROOTFS"
fi

echo "[80bee] Verifying Ubuntu PRoot Container..."
if [ ! -d "$UBUNTU_ROOTFS/etc" ]; then
    echo "[80bee] Installing fresh Ubuntu PRoot..."
    if ! proot-distro install ubuntu; then
        echo "[80bee] ERROR: proot-distro failed to download/extract Ubuntu! Aborting."
        exit 1
    fi
else
    echo "[80bee] Valid Ubuntu container already exists. Skipping download cache."
fi

mkdir -p "$UBUNTU_ROOTFS/root"

echo "[80bee] Injecting Pi-hole setup routines into Ubuntu..."
cat << 'EOF' > "$UBUNTU_ROOTFS/root/build_pihole.sh"
#!/bin/bash
export DEBIAN_FRONTEND=noninteractive
export TZ=UTC

# Update packages
apt-get update -y
apt-get upgrade -y
apt-get install -y curl wget git cron iproute2 dialog nano tzdata iputils-ping

# Setup missing directories for Pi-hole
mkdir -p /etc/pihole /etc/lighttpd
touch /etc/pihole/setupVars.conf

# We will skip the OS check and network check since PRoot environments mock network interfaces
# Set essential vars
cat << 'VARS' > /etc/pihole/setupVars.conf
PIHOLE_INTERFACE=eth0
IPV4_ADDRESS=127.0.0.1/24
IPV6_ADDRESS=
QUERY_LOGGING=true
INSTALL_WEB_INTERFACE=true
LIGHTTPD_ENABLED=true
CACHE_SIZE=10000
DNSMASQ_LISTENING=single
PIHOLE_DNS_1=1.1.1.1
PIHOLE_DNS_2=1.0.0.1
DNS_FQDN_REQUIRED=true
DNS_BOGUS_PRIV=true
DNSSEC=false
REV_SERVER=false
VARS

echo "[80bee] Downloading Pi-hole Installer..."
wget -O basic-install.sh https://install.pi-hole.net

echo "[80bee] Running Pi-hole Unattended Setup (v6 Compatible)..."
# Override OS check and install
PIHOLE_SKIP_OS_CHECK=true bash basic-install.sh --unattended

echo "[80bee] Adjusting Port Configurations (Rootless Compatibility for Pi-hole v6)..."
# Pi-hole v6 deprecated lighttpd and handles both Web UI and DNS natively via FTL.
pihole-FTL --config dns.port 5353
pihole-FTL --config webserver.port 8080

echo "[80bee] Setting Web UI Password to 'admin'..."
pihole setpassword admin || pihole -a -p admin || true

echo "----------------------------------------------------"
echo "[✓] 80bee Pi-hole Installation Complete!"
echo "----------------------------------------------------"
echo "DNS Port: 127.0.0.1:5353"
echo "Web Admin Dashboard: http://127.0.0.1:8080/admin"
echo "Password: admin"
echo ""
echo "[80bee] Starting Pi-hole FTL in foreground mode..."
echo "[80bee] Keep this Termux session open to maintain the service!"
echo "----------------------------------------------------"

# Kill any existing FTL instance before starting fresh
killall pihole-FTL 2>/dev/null || true
sleep 1

# Start FTL in no-daemon (foreground) mode so the PRoot session stays alive.
# Without this, exiting the script kills the PRoot container and all services.
exec pihole-FTL -f
EOF

chmod +x "$UBUNTU_ROOTFS/root/build_pihole.sh"

# Also create a lightweight restart script for future use
cat << 'START' > "$UBUNTU_ROOTFS/root/start_pihole.sh"
#!/bin/bash
echo "[80bee] Starting Pi-hole FTL..."
killall pihole-FTL 2>/dev/null || true
sleep 1
echo "DNS Port: 127.0.0.1:5353"
echo "Web Admin Dashboard: http://127.0.0.1:8080/admin"
exec pihole-FTL -f
START
chmod +x "$UBUNTU_ROOTFS/root/start_pihole.sh"

echo "[80bee] Booting Ubuntu PRoot and Executing Payload..."
echo "[80bee] NOTE: Pi-hole will keep running in this terminal. Do NOT close Termux!"
# Login to proot and execute. We bind /dev/null to cap_last_cap to avoid known PRoot issues
proot-distro login ubuntu --bind /dev/null:/proc/sys/kernel/cap_last_cap -- /root/build_pihole.sh
