#!/bin/bash

# blob:summary=Report NetBird status, connect, disconnect, sign in, and switch profiles
# blob:args=<status|summary|up|down|login|profiles|select <name>|add <name>|remove <name>>
# blob:group=network

set -uo pipefail

action="${1-status}"
profile_name="${2-}"

require_profile_name() {
  if [[ ! $profile_name =~ ^[A-Za-z0-9._-]+$ ]]; then
    echo "Profile names may use letters, digits, dots, dashes, and underscores" >&2
    exit 2
  fi
}

daemon_status() {
  netbird status --json 2>/dev/null | jq -r '.daemonStatus // ""'
}

if ! command -v netbird >/dev/null 2>&1; then
  case "$action" in
    status) echo '{"installed":false}' ;;
    profiles) echo '[]' ;;
    summary) echo "Not installed" ;;
    *) echo "NetBird is not installed" >&2; exit 1 ;;
  esac
  exit 0
fi

case "$action" in
  status)
    if ! netbird status --json 2>/dev/null | jq -c '. + {installed: true}'; then
      echo '{"installed":true,"daemonStatus":"DaemonDown"}'
    fi
    ;;
  summary)
    netbird status --json 2>/dev/null | jq -r '
      (if .daemonStatus == "Connected" then "Connected · \(.peers.connected // 0)/\(.peers.total // 0) peers"
      elif .daemonStatus == "NeedsLogin" or .daemonStatus == "LoginFailed" then "Signed out"
      elif .daemonStatus == "Connecting" then "Connecting…"
      else "Disconnected" end)
      + (if (.profileName // "default") != "default" then " \u00b7 \(.profileName)" else "" end)' || echo "Service not running"
    ;;
  up)
    netbird up 2>&1 | tail -n 3
    ;;
  down)
    netbird down 2>&1 | tail -n 3
    ;;
  login)
    blob-terminal-exec bash -c 'netbird up; echo; read -rp "Press Enter to close"'
    ;;
  profiles)
    netbird profile list 2>/dev/null | tail -n +2 | jq -R -s -c '
      split("\n") | map(select(test("\\S"))) |
      map(capture("^\\s*(?<name>\\S+)\\s*(?<mark>\\*?)\\s*$") | {name, active: (.mark == "*")})'
    ;;
  select)
    require_profile_name
    was_connected=$([[ $(daemon_status) == Connected ]] && echo yes)
    netbird down >/dev/null 2>&1
    netbird profile select "$profile_name" 2>&1 | tail -n 2 || exit 1
    if [[ -n $was_connected && $(daemon_status) != NeedsLogin ]]; then
      timeout 30 netbird up 2>&1 | tail -n 2
    fi
    ;;
  add)
    require_profile_name
    netbird profile add "$profile_name" 2>&1 | tail -n 2
    ;;
  remove)
    require_profile_name
    netbird profile remove "$profile_name" 2>&1 | tail -n 2
    ;;
  *)
    echo "Usage: blob-netbird <status|summary|up|down|login|profiles|select <name>|add <name>|remove <name>>" >&2
    exit 2
    ;;
esac
