#!/bin/bash

source /opt/scripts_local/shared_functions.sh

REF_VERS=$(_get_latest_version "tailscale/tailscale")
REF_VERS=$(echo "$REF_VERS" | cut -c 2-)  # removes the v of the version string
REF_VERS=$(echo "$REF_VERS" | cut -d "," -f 1) # removes the , and the rest of the version string
INSTALLED_VERS=$(tailscale --version)
INSTALLED_VERS=$(echo "$INSTALLED_VERS" | head -1) # keeps the first line of the version string

# if [ "$INSTALLED_VERS" != "$REF_VERS" ] ; then
#   curl -fsSL https://tailscale.com/install.sh | sudo sh
#   export TAIL_HOSTNAME="--hostname="$HOSTNAME
#   export TAIL_ACCEPT_DNS="--accept-dns=true"
#   export TAIL_OPERATOR="--operator=dbi"
#   export TAIL_SSH="--ssh"
#   export TAIL_ACCEPT_ROUTES="--accept-routes=true"
#   sudo tailscale up \
#   "$TAIL_SSH" \
#   "$TAIL_ACCEPT_DNS" \
#   "$TAIL_ACCEPT_ROUTES" \
#   "$TAIL_OPERATOR" \
#   "$TAIL_HOSTNAME" 
#   sudo tailscale set --auto-update
# fi

if ! ( type -p tailscale >/dev/null ); then
  echo "Tailscale not detected, installing ..."
  MY_NETMASK="192.168.10.0/24"
  #MY_NETMASK="192.168.$MY_NET".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
  # MY_API_KEY=$(ssh -o StrictHostKeyChecking=no -t dbi@vmx-nas.home cat /mnt/union/shared/home/denis/tail.key)
  # Attention !!!! $MY_API_KEY doit finir avec un : pour clairement dire qu'il n'y a pas de password
  MY_AUTH_KEY=$(curl -u "$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
