#!/bin/bash
# to bind this to 443, root privileges are required. start this like 
# sudo -E PATH="$PATH" bash ./start_frontend_https.sh
# Unified startup script: generates certs if needed, starts HTTPS Streamlit and HTTP->HTTPS redirector

# Dynamically select per-device cert and key based on hostname and Avahi domain
DEVICE_HOSTNAME=$(hostname)
AVAHI_CONF="/etc/avahi/avahi-daemon.conf"
AVAHI_DOMAIN=$(awk -F= '/^\s*domain-name\s*=/{gsub(/ /, "", $2); print $2}' "$AVAHI_CONF")
if [ -z "$AVAHI_DOMAIN" ]; then
  AVAHI_DOMAIN=local
fi
CERT_DIR="certs/per_device/${DEVICE_HOSTNAME}.${AVAHI_DOMAIN}"
CERT="$CERT_DIR/device_cert.pem"
KEY="$CERT_DIR/device_key.pem"
CA_CERT="certs/ca/ca_cert.pem"

if [ ! -f "$CERT" ] || [ ! -f "$KEY" ]; then
  echo "ERROR: Device certificate or key not found in $CERT_DIR. Run provision_domain_hostname.sh first."
  exit 1
fi

if [ ! -f "$CA_CERT" ]; then
  echo "WARNING: CA certificate not found at $CA_CERT. HTTPS will work, but clients may not be able to import the CA."
fi

echo "CA cert: $CA_CERT"
echo "Device cert: $CERT"
echo "Device key: $KEY"
echo "Using hostname: $DEVICE_HOSTNAME"
echo "Using Avahi domain: $AVAHI_DOMAIN"

# Path to poetry binary
POETRY_BIN="/home/caster/.local/bin/poetry"

# Start HTTP->HTTPS redirect server on port 80 (background)
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
python3 "$SCRIPT_DIR/http_to_https_redirect.py" 80 &
REDIRECT_PID=$!
echo "HTTP->HTTPS redirect server started (PID $REDIRECT_PID)"
trap "kill $REDIRECT_PID 2>/dev/null" EXIT

# Start Streamlit HTTPS server (port 443)
$POETRY_BIN run streamlit run multicast_frontend.py --server.port 443 --server.address 0.0.0.0 --server.enableCORS false --server.enableXsrfProtection false --server.headless true --server.sslCertFile "$CERT" --server.sslKeyFile "$KEY" --browser.gatherUsageStats false
