#!/bin/bash

TAIL_HOSTNAME="--hostname="$HOSTNAME
TAIL_ACCEPT_DNS="--accept-dns=true"
TAIL_OPERATOR="--operator=dbi"
TAIL_SSH="--ssh"
TAIL_ACCEPT_ROUTES="--accept-routes=true"

type -p curl >/dev/null || (sudo apt update && sudo apt install curl -y)
rsync >/dev/null 2>&1 || (sudo apt update && sudo apt install rsync -y)


read -p "Tailscale API Key: " TAIL_MY_API_KEY


if ! ( type -p tailscale >/dev/null ); then
  echo "Tailscale not detected, installing ..."
  MY_NETMASK="192.168.10.0/24"
  sudo ip rule add to "$MY_NETMASK" priority 2500 lookup main
  sudo touch /etc/cron.d/tailscale_lan_access
  echo "@reboot root sleep 10 && ip rule add to $MY_NETMASK priority 2500 lookup main" | sudo tee /etc/cron.d/tailscale_lan_access
  sudo chmod 600 /etc/cron.d/tailscale_lan_access
  # $TAIL_MY_API_KEY needs to have a : at the end in order to specify that no pwd is provided
  MY_AUTH_KEY=$(curl -u "$TAIL_MY_API_KEY:" https://api.tailscale.com/api/v2/tailnet/sukkeler@gmail.com/keys   --data-binary '
  {
    "capabilities": {
      "devices": {
        "create": {
          "reusable": false,
          "ephemeral": false,
          "preauthorized": true
        }
      }
    },
    "expirySeconds": 86400,
    "description": "dev access"
  }' | grep -o '"key":"[^"]*' | grep -o '[^"]*$')
  TAIL_AUTH="--authkey=$MY_AUTH_KEY"
  curl -fsSL https://tailscale.com/install.sh | sudo sh
  sudo tailscale up \
  "$TAIL_SSH" \
  "$TAIL_ACCEPT_DNS" \
  "$TAIL_ACCEPT_ROUTES" \
  "$TAIL_OPERATOR" \
  "$TAIL_HOSTNAME" \
  "$TAIL_AUTH"
  sudo tailscale set --auto-update
else
  echo "Tailscale already installed skipping."
fi



