#!/bin/bash

tailscale='/Applications/Tailscale.app/Contents/MacOS/Tailscale'

# Get local IP
local_ip=$(hostname -I | awk '{print $1}')
wan_info=$(curl -s --max-time 10 https://am.i.mullvad.net/json)
wan_connected=false
if [ ! -z "$wan_info" ]; then
  wan_connected=true
  wan_ip=$(echo "$wan_info" | jq -r '.ip')
  mullvad_exit_ip=$(echo "$wan_info" | jq '.mullvad_exit_ip')
  blacklisted=$(echo "$wan_info" | jq '.blacklisted.blacklisted')
else
  wan_ip="Unavailable"
fi

# Check if Tailscale is installed and get IP
if command -v $tailscale &> /dev/null; then
  has_tailscale=true
  tailscale_ip=$($tailscale ip -4)
  # Get Tailscale exit-node information
  ts_exitnode_output=$($tailscale exit-node list)
  # Parse exit node hostname
  if echo "$ts_exitnode_output" | grep -q 'selected'; then
    mullvad_exitnode=true
    # Extract the hostname of the selected exit node
    mullvad_hostname=$(echo "$ts_exitnode_output" | grep 'selected' | awk '{print $2}')
  else
    mullvad_exitnode=false
    mullvad_hostname=""
  fi
else
  has_tailscale=false
  tailscale_ip="Not installed"
  mullvad_exitnode=false
  mullvad_hostname=""
fi

nextdns_info=$(curl -sL --max-time 10 https://test.nextdns.io)
if [ -z "$nextdns_info" ]; then
  echo "Failed to fetch NextDNS status or no internet connection."
else
  nextdns_status=$(echo "$nextdns_info" | jq -r '.status')
  if [ "$nextdns_status" = "unconfigured" ]; then
    echo "You are not using NextDNS."
    nextdns_connected=false
    nextdns_protocol=""
    nextdns_client=""
  else
    nextdns_connected=true
    nextdns_protocol=$(echo "$nextdns_info" | jq -r '.protocol')
    nextdns_client=$(echo "$nextdns_info" | jq -r '.clientName')
    echo "Connected to NextDNS via $nextdns_protocol. Client: $nextdns_client."
  fi
fi

# read uptime_seconds _ < /proc/uptime
# uptime_days=$(echo "$uptime_seconds / 86400" | bc -l)
# uptime_rounded=$(printf "%.2f" $uptime_days)

cat <<EOF
{
  "local_ip": "$local_ip",
  "wan_connected": $wan_connected,
  "wan_ip": "$wan_ip",
  "has_tailscale": $has_tailscale,
  "tailscale_ip": "$tailscale_ip",
  "mullvad_exitnode": $mullvad_exitnode,
  "mullvad_hostname": "$mullvad_hostname",
  "mullvad_exit_ip": $mullvad_exit_ip,
  "blacklisted": $blacklisted,
  "nextdns_connected": $nextdns_connected,
  "nextdns_protocol": "$nextdns_protocol",
  "nextdns_client": "$nextdns_client",
  "uptime": ""
}