#!/bin/bash
# frpc deployment script for TrueNAS
# Run from Fedora: bash plans/frpc-truenas-deploy.sh
# Installs frpc on TrueNAS and sets up tunnel to expose Gitea publicly

TRUENAS="root@192.168.188.119"
VPS_IP="85.214.154.199"
FRP_TOKEN="5f64a6f20bb2cb8c3133ecac8ca3f0571d7d64dff910225040bfc0c60a106c81"
FRP_VERSION="0.68.1"

echo "=== Deploying frpc on TrueNAS ==="

ssh -i /home/pplate/.ssh/id_ed25519_homelab $TRUENAS << REMOTE
set -e

# TrueNAS root filesystem is read-only — install to /mnt which is persistent ZFS
INSTALL_DIR=/mnt/VM_SSD_Pool/frp
mkdir -p \$INSTALL_DIR

# Download frpc binary
echo "Downloading frp ${FRP_VERSION}..."
curl -sL https://github.com/fatedier/frp/releases/download/v${FRP_VERSION}/frp_${FRP_VERSION}_linux_amd64.tar.gz \
  -o /tmp/frp.tar.gz
tar xzf /tmp/frp.tar.gz -C /tmp/
cp /tmp/frp_${FRP_VERSION}_linux_amd64/frpc \$INSTALL_DIR/frpc
chmod +x \$INSTALL_DIR/frpc
\$INSTALL_DIR/frpc --version

# Write frpc config
cat > \$INSTALL_DIR/frpc.toml << 'TOML'
serverAddr = "${VPS_IP}"
serverPort = 7000
auth.method = "token"
auth.token = "${FRP_TOKEN}"
log.to = "/tmp/frpc.log"
log.level = "info"

[[proxies]]
name = "gitea"
type = "tcp"
localIP = "127.0.0.1"
localPort = 30008
remotePort = 30008
TOML

echo "frpc config written:"
cat \$INSTALL_DIR/frpc.toml

# Create init script (TrueNAS uses systemd-like init but custom)
# Use /etc/local.d/ for persistent startup scripts on TrueNAS SCALE
# Actually TrueNAS SCALE uses systemd — write a service to /etc/systemd/system/
cat > /etc/systemd/system/frpc.service << 'SVCEOF'
[Unit]
Description=frp client - tunnel to plate.software VPS
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/mnt/VM_SSD_Pool/frp/frpc -c /mnt/VM_SSD_Pool/frp/frpc.toml
Restart=on-failure
RestartSec=10s

[Install]
WantedBy=multi-user.target
SVCEOF

systemctl daemon-reload
systemctl enable frpc
systemctl start frpc
sleep 3
systemctl status frpc --no-pager | head -15
echo ""
echo "=== frpc deployed and running ==="
echo "Gitea should now be reachable at https://git.plate.software"
REMOTE
