#!/bin/bash
#
# Purpose : Set up this Mac for your Federated Core (Mail, Calendar,
#           Contacts, Superpanel, files, Element, Tailscale, backups) and its
#           network (shared folders, AI servers), and AI agents in a sandbox.
#           The apps macOS doesn't come with are offered for download.
#
# Each file in configure.d/ is one item. It sets TITLE and DESCRIPTION and
# defines is_configured and run_configure. It can also define is_installed;
# the item is left out when that fails. To add an item, add a file there.
#
# This runs with the bash macOS comes with (3.2), so it doesn't use mapfile,
# read -i, associative arrays or ${var,,}, and it uses only tools that are
# part of macOS (plutil, xmllint, osascript, security, profiles), not jq or
# python3, which need the Command Line Tools.

# Wrapped in { ...; exit; } so bash reads the whole script up front; an update
# can then replace this file while it runs.
{

if [ "$(uname -s)" != Darwin ]; then
  echo "This is for macOS. On Linux, use CoreDesktop's configure."
  exit 1
fi
MACOS_MAJOR="$(sw_vers -productVersion | cut -d. -f1)"
if [ "$MACOS_MAJOR" -lt 13 ] 2> /dev/null; then
  echo "This needs macOS 13 (Ventura) or later."
  exit 1
fi

# The directory this script is in, following symlinks, so it can be linked
# into a directory on PATH
script_dir() {
  local file="$0" link
  while [ -L "$file" ]; do
    link="$(readlink "$file")"
    case "$link" in
      /*) file="$link" ;;
      *) file="$(dirname "$file")/$link" ;;
    esac
  done
  cd "$(dirname "$file")" && pwd
}

CONNECTOR="$(script_dir)"
CONF_DIR="$HOME/Library/Application Support/Federated Connector"
COMPUTER="$(scutil --get ComputerName 2> /dev/null || hostname -s)"

RED=$'\033[31m' GREEN=$'\033[32m' YELLOW=$'\033[33m' BOLD=$'\033[1m' RESET=$'\033[0m'

# Ask a yes/no question; the default is no
confirm() {
  local answer
  read -rp "$1 [y/N] " answer
  [[ "$answer" == [yY]* ]]
}

# Ask a yes/no question; the default is yes
confirm_yes() {
  local answer
  read -rp "$1 [Y/n] " answer
  [[ "$answer" != [nN]* ]]
}

# ask <variable> <question> [default]: Enter alone keeps the default (bash
# 3.2's read can't put it on the line to edit)
ask() {
  local answer
  if [ -n "$3" ]; then
    read -rp "$2 [$3]: " answer
  else
    read -rp "$2: " answer
  fi
  printf -v "$1" '%s' "${answer:-$3}"
}

# wait_until <seconds> <command> [args]: run the command every 2 seconds until
# it succeeds, you press Enter, or time runs out. Fails unless it succeeded.
wait_until() {
  local seconds="$1" waited=0 key
  shift
  echo "(Waiting; press Enter to stop waiting.)"
  while [ "$waited" -lt "$seconds" ]; do
    "$@" && return 0
    if read -r -t 2 key; then
      "$@"
      return
    fi
    waited=$((waited + 2))
  done
  "$@"
}

usage() {
  cat << EOF
Usage: configure [item]

  configure          Show what's set up and choose what to set up
  configure <item>   Set up one item
  configure --list   Show what's set up, and the item names

EOF
}

# configure.d/10-core.sh -> core
item_name() {
  local name
  name="$(basename "$1" .sh)"
  echo "${name#[0-9][0-9]-}"
}

# Prints "<state>|<title>|<description>"; state is done, todo or absent
# shellcheck disable=SC2153
item_info() {
  (
    source "$1"
    if declare -f is_installed > /dev/null && ! is_installed &> /dev/null; then
      echo "absent||"
    elif is_configured &> /dev/null; then
      echo "done|$TITLE|$DESCRIPTION"
    else
      echo "todo|$TITLE|$DESCRIPTION"
    fi
  )
}

configure_item() {
  (
    source "$1"
    echo
    echo "$BOLD$TITLE$RESET"
    run_configure
  )
  local status=$?
  if [ $status -ne 0 ]; then
    echo "$RED$(item_name "$1") was not set up.$RESET"
  fi
  return $status
}

# Fill ITEMS, STATES, TITLES and DESCRIPTIONS with the installed items
load_items() {
  local file state title description
  ITEMS=()
  STATES=()
  TITLES=()
  DESCRIPTIONS=()
  for file in "$CONNECTOR"/configure.d/*.sh; do
    [ -f "$file" ] || continue
    IFS='|' read -r state title description < <(item_info "$file")
    [ "$state" = absent ] && continue
    ITEMS+=("$file")
    STATES+=("$state")
    TITLES+=("$title")
    DESCRIPTIONS+=("$description")
  done
}

show_items() {
  local i mark
  for i in "${!ITEMS[@]}"; do
    if [ "${STATES[$i]}" = "done" ]; then
      mark="${GREEN}done$RESET "
    else
      mark="${YELLOW}to do$RESET"
    fi
    printf "  %2d) %s  %-22s %s\n" $((i + 1)) "$mark" "${TITLES[$i]}" "${DESCRIPTIONS[$i]}"
  done
}

case "$1" in
  "") ;;
  -h|--help)
    usage
    exit 0 ;;
  -l|--list)
    load_items
    for i in "${!ITEMS[@]}"; do
      printf '%-6s %-14s %s\n' "${STATES[$i]/todo/to do}" "$(item_name "${ITEMS[$i]}")" "${TITLES[$i]}"
    done
    exit 0 ;;
  *)
    for file in "$CONNECTOR"/configure.d/*.sh; do
      if [ "$(item_name "$file")" = "$1" ]; then
        configure_item "$file"
        exit
      fi
    done
    echo "No item named $1. These are: configure --list"
    exit 2 ;;
esac

while true; do
  load_items
  echo
  echo "Federated Core on this Mac"
  echo
  show_items
  echo
  echo "   a) Set up everything still to do"
  echo "   q) Quit"
  echo
  read -rp "Choose: " choice || exit 0

  case "$choice" in
    q|Q|"")
      exit 0 ;;
    a|A)
      for i in "${!ITEMS[@]}"; do
        [ "${STATES[$i]}" = todo ] && configure_item "${ITEMS[$i]}"
      done ;;
    *)
      if [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 1 ] && [ "$choice" -le ${#ITEMS[@]} ]; then
        configure_item "${ITEMS[$((choice - 1))]}"
      else
        echo "Choose a number from the list, a or q."
      fi ;;
  esac
done
}
