#!/usr/bin/env bash
#
# Install host-side systemd services for cistech-tunnel
# Run this ONCE on the host after installing the app in Runtipi
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_DATA_DIR="/etc/runtipi/app-data/runtipi/cistech-tunnel"

echo "Installing cistech-tunnel host services..."

# Create the path watcher unit
cat << 'EOF' | sudo tee /etc/systemd/system/cistech-routing-watcher.path
[Unit]
Description=Watch for cistech-tunnel routing trigger

[Path]
PathExists=/etc/runtipi/app-data/runtipi/cistech-tunnel/restart-routing
Unit=cistech-routing-watcher.service

[Install]
WantedBy=multi-user.target
EOF

# Create the service unit
cat << EOF | sudo tee /etc/systemd/system/cistech-routing-watcher.service
[Unit]
Description=Apply cistech-tunnel routing rules
After=docker.service

[Service]
Type=oneshot
ExecStart=/bin/bash ${SCRIPT_DIR}/host-routing.sh restart
ExecStartPost=/bin/rm -f ${APP_DATA_DIR}/restart-routing
ExecStartPost=/bin/bash -c 'echo "trigger cleared at \$(date)" >> ${APP_DATA_DIR}/watcher.log'
EOF

# Make host-routing.sh executable
sudo chmod +x "${SCRIPT_DIR}/host-routing.sh"

# Reload systemd and enable the watcher
sudo systemctl daemon-reload
sudo systemctl enable --now cistech-routing-watcher.path

echo ""
echo "Done! Services installed:"
echo "  - cistech-routing-watcher.path (watches for trigger file)"
echo "  - cistech-routing-watcher.service (applies routing rules)"
echo ""
echo "To check status:"
echo "  systemctl status cistech-routing-watcher.path"
echo ""
echo "To manually trigger routing:"
echo "  touch ${APP_DATA_DIR}/restart-routing"
