#!/bin/bash
set -o errexit
set -o xtrace

curl -fsSL https://pkgs.tailscale.com/stable/ubuntu/oracular.noarmor.gpg | sudo tee /usr/share/keyrings/tailscale-archive-keyring.gpg >/dev/null
curl -fsSL https://pkgs.tailscale.com/stable/ubuntu/oracular.tailscale-keyring.list | sudo tee /etc/apt/sources.list.d/tailscale.list
sudo apt-get update && sudo apt-get -y install apt-transport-https ca-certificates curl tailscale

echo 'net.ipv4.ip_forward = 1' | sudo tee -a /etc/sysctl.d/99-tailscale.conf
echo 'net.ipv6.conf.all.forwarding = 1' | sudo tee -a /etc/sysctl.d/99-tailscale.conf
sudo sysctl -p /etc/sysctl.d/99-tailscale.conf

NETDEV=$(ip -o route get 8.8.8.8 | cut -f 5 -d " ")
sudo ethtool -K $NETDEV rx-udp-gro-forwarding on rx-gro-list off

set +o xtrace
echo "Fetching Tailscale OAuth Secret"
project_id=$(curl --silent "http://metadata.google.internal/computeMetadata/v1/project/numeric-project-id" -H "Metadata-Flavor: Google")
secret_id="<<SECRET_ID>>"
token=$(curl --silent "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" -H "Metadata-Flavor: Google" | jq .access_token -r)
TS_OAUTH_SECRET=$(curl --silent "https://secretmanager.googleapis.com/v1beta1/projects/${project_id}/secrets/${secret_id}/versions/latest:access" -H "Authorization: Bearer ${token}" | jq '.payload.data |= @base64d | .payload.data' -r)

tailscale_tag_name="<<TAILSCALE_TAG_NAME>>"
advertised_routes="<<ADVERTISED_ROUTES>>"

attempt=1
max_attempts=3
while [ "$attempt" -le "$max_attempts" ]; do
  # https://tailscale.com/kb/1019/subnets?tab=linux#advertise-subnet-routes
  echo "Starting tailscale (attempt $attempt/$max_attempts)..."
  sudo tailscale up \
    --authkey="$TS_OAUTH_SECRET?preauthorized=true&ephemeral=true" \
    --hostname=${tailscale_tag_name}-$(hostname | cut -d. -f1) \
    --advertise-routes=${advertised_routes} \
    --advertise-tags=tag:${tailscale_tag_name} \
    --accept-dns=false
  sleep 5
  sudo tailscale status
  if [ $? == 0 ]; then
    echo "tailscale is active on attempt #$attempt"
    break
  else
    echo "tailscale is not active yet."
    (( attempt++ ))
  fi
done
set -o xtrace

# https://tailscale.com/kb/1482/client-metrics#expose-metrics-to-other-networks
cat << 'EOF' > /etc/systemd/system/tailscale-metrics.service
[Unit]
Description=Tailscale Metrics Web Interface
Requires=tailscaled.service
After=network.target tailscaled.service

[Service]
Type=simple
ExecStart=tailscale web --readonly --listen 0.0.0.0:5252
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable tailscale-metrics
systemctl start tailscale-metrics
