#!/bin/bash
# Copyright 2025 Hedgehog
# SPDX-License-Identifier: Apache-2.0

# Start Loki and Prometheus port-forwards for LAN access, using multiple loopbacks

set -euo pipefail

export KUBECONFIG=/home/pau/fabricator/vlab/kubeconfig
NAMESPACE="lgtm"

HOST_IP=$(hostname -I | awk '{print $1}')

# Cleanup background jobs and iptables on exit
cleanup() {
	echo -e "\nStopping all port-forwards..."
	kill $(jobs -p) 2>/dev/null || true
	echo "Removing iptables rules..."
	sudo iptables -t nat -D OUTPUT -p tcp -d 127.0.0.2 --dport 80 -j REDIRECT --to-port 3100 2>/dev/null || true
	sudo iptables -t nat -D OUTPUT -p tcp -d 127.0.0.3 --dport 80 -j REDIRECT --to-port 9090 2>/dev/null || true
	exit
}
trap cleanup INT TERM

wait_for_port() {
	local port=$1
	local name=$2
	local timeout=${3:-30}
	local count=0
	echo "Waiting for $name port $port..."
	while ! nc -z localhost "$port" && [ $count -lt $timeout ]; do
		sleep 0.5
		count=$((count + 1))
	done
	if [ $count -lt $timeout ]; then
		echo "$name is ready on port $port"
		return 0
	else
		echo "Timed out waiting for $name on port $port"
		return 1
	fi
}

# Start port-forwards in background (service port 80 for both)
echo "Starting port-forwards..."
kubectl -n $NAMESPACE port-forward svc/loki-gateway 3100:80 &
kubectl -n $NAMESPACE port-forward svc/prometheus-server 9090:80 &

# Wait until local ports are reachable
wait_for_port 3100 "Loki Gateway"
wait_for_port 9090 "Prometheus"

# Set up iptables for service name access using separate loopbacks
echo "Setting up iptables for service name access (multi-loopback)..."
sudo iptables -t nat -A OUTPUT -p tcp -d 127.0.0.2 --dport 80 -j REDIRECT --to-port 3100
sudo iptables -t nat -A OUTPUT -p tcp -d 127.0.0.3 --dport 80 -j REDIRECT --to-port 9090

echo -e "\nPort forwards and proxies are ready!"
echo "Loki is available at: http://loki-gateway.lgtm.svc.cluster.local/loki/api/v1/"
echo "Prometheus is available at: http://prometheus-server.lgtm.svc.cluster.local/api/v1/"
echo "Test Prometheus: curl -s \"http://prometheus-server.lgtm.svc.cluster.local/api/v1/query?query=up\""
echo "Test Loki: curl -s \"http://loki-gateway.lgtm.svc.cluster.local/loki/api/v1/label/hostname/values\""
echo -e "\nPress Ctrl+C to stop all port-forwards and remove iptables rules."

# Wait for all background jobs
wait
