#!/usr/bin/env bash
# tunl client one-command installer (hosted at https://get.cles.tech/install.sh)
#
# First install:
#   curl -fsSL https://get.cles.tech/install.sh | sudo TUNL_TOKEN=<token> bash -s -- -tunnel app=3000 -tunnel api=8080
#
# Update binary only (keeps existing config):
#   curl -fsSL https://get.cles.tech/install.sh | sudo bash
set -euo pipefail

BASE="${BASE:-https://get.cles.tech}"
SERVER="${SERVER:-144.24.186.230:7000}"
FINGERPRINT="${FINGERPRINT:-02dd02e883e090cfab82942f3767340588837ab66a22b3960c2b194160df3f71}"

[ "$(id -u)" = 0 ] || { echo "run as root (pipe into: sudo bash)"; exit 1; }
command -v systemctl >/dev/null || { echo "needs a systemd Linux host"; exit 1; }

case "$(uname -m)" in
  x86_64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) echo "unsupported arch: $(uname -m)"; exit 1 ;;
esac

echo "downloading tunl-linux-$ARCH ..."
curl -fsSL "$BASE/tunl-linux-$ARCH" -o /usr/local/bin/tunl.tmp
chmod 755 /usr/local/bin/tunl.tmp
mv /usr/local/bin/tunl.tmp /usr/local/bin/tunl
curl -fsSL "$BASE/tunl-client.service" -o /etc/systemd/system/tunl-client.service

if [ "$#" -gt 0 ]; then
  # Fresh configuration: needs token + tunnel list
  TOKEN="${TUNL_TOKEN:-}"
  [ -n "$TOKEN" ] || { echo "TUNL_TOKEN not set. Usage:
  curl -fsSL $BASE/install.sh | sudo TUNL_TOKEN=<token> bash -s -- -tunnel app=3000"; exit 1; }
  mkdir -p /etc/tunl
  cat > /etc/tunl/client.env <<EOF
TUNL_TOKEN=$TOKEN
TUNL_FINGERPRINT=$FINGERPRINT
SERVER=$SERVER
TUNNELS=$*
EOF
  chmod 600 /etc/tunl/client.env
elif [ ! -f /etc/tunl/client.env ]; then
  echo "no existing config and no tunnels given. Usage:
  curl -fsSL $BASE/install.sh | sudo TUNL_TOKEN=<token> bash -s -- -tunnel app=3000"; exit 1
fi

systemctl daemon-reload
systemctl enable --now tunl-client >/dev/null 2>&1
systemctl restart tunl-client
sleep 2
systemctl --no-pager --lines 4 status tunl-client || true
echo
echo "done — edit /etc/tunl/client.env and 'systemctl restart tunl-client' to change tunnels"
