#!/usr/bin/env bash
# Linux Mint desktop bootstrap
#
# Run as the desktop user:
#   curl -fsSL https://example.invalid/mint-bootstrap.sh | bash
#
# The script asks for sudo once, installs system-wide software, then switches
# back to the invoking desktop user for NVM, Node/npm, and the OpenCode CLI.

set -Eeuo pipefail
IFS=$'\n\t'

readonly NVM_VERSION="v0.40.7"
readonly NETBIRD_KEY_URL="https://pkgs.netbird.io/debian/public.key"
readonly NETBIRD_REPOSITORY="https://pkgs.netbird.io/debian stable main"
readonly CHROME_DEB_URL="https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb"
readonly VSCODE_DEB_URL="https://code.visualstudio.com/sha/download?build=stable&os=linux-deb-x64"
readonly OPENCODE_DESKTOP_DEB_URL="https://github.com/anomalyco/opencode/releases/latest/download/opencode-desktop-linux-amd64.deb"

info() {
  printf '\n==> %s\n' "$*"
}

die() {
  printf '\nERROR: %s\n' "$*" >&2
  exit 1
}

on_error() {
  local exit_code=$?
  printf '\nERROR: command failed (exit %s): %s\n' "$exit_code" "$BASH_COMMAND" >&2
  exit "$exit_code"
}

trap on_error ERR

if [[ -n "${SUDO_USER:-}" && "${SUDO_USER}" != "root" ]]; then
  readonly TARGET_USER="$SUDO_USER"
else
  readonly TARGET_USER="$(id -un)"
fi

[[ "$TARGET_USER" != "root" ]] || die "Run this from the desktop user's terminal, not directly as root."
readonly TARGET_HOME="$(getent passwd "$TARGET_USER" | awk -F: '{print $6}')"
[[ -n "$TARGET_HOME" && -d "$TARGET_HOME" ]] || die "Could not determine the home directory for $TARGET_USER."

readonly TARGET_DISPLAY="${DISPLAY:-}"
readonly TARGET_WAYLAND_DISPLAY="${WAYLAND_DISPLAY:-}"
readonly TARGET_XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-}"
readonly TARGET_DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-}"

readonly STATE_DIR="$TARGET_HOME/.local/state/mint-bootstrap"
mkdir -p "$STATE_DIR"
exec > >(tee -a "$STATE_DIR/bootstrap.log") 2>&1

work_dir="$(mktemp -d -t mint-bootstrap.XXXXXX)"
cleanup() {
  rm -rf -- "$work_dir"
}
trap cleanup EXIT

as_root() {
  if (( EUID == 0 )); then
    "$@"
  else
    sudo "$@"
  fi
}

run_as_target() {
  if [[ "$(id -un)" == "$TARGET_USER" ]]; then
    env \
      HOME="$TARGET_HOME" \
      USER="$TARGET_USER" \
      DISPLAY="$TARGET_DISPLAY" \
      WAYLAND_DISPLAY="$TARGET_WAYLAND_DISPLAY" \
      XDG_RUNTIME_DIR="$TARGET_XDG_RUNTIME_DIR" \
      DBUS_SESSION_BUS_ADDRESS="$TARGET_DBUS_SESSION_BUS_ADDRESS" \
      bash -s
  else
    as_root runuser -u "$TARGET_USER" -- env \
      HOME="$TARGET_HOME" \
      USER="$TARGET_USER" \
      DISPLAY="$TARGET_DISPLAY" \
      WAYLAND_DISPLAY="$TARGET_WAYLAND_DISPLAY" \
      XDG_RUNTIME_DIR="$TARGET_XDG_RUNTIME_DIR" \
      DBUS_SESSION_BUS_ADDRESS="$TARGET_DBUS_SESSION_BUS_ADDRESS" \
      bash -s
  fi
}

download() {
  local url=$1
  local destination=$2
  curl --fail --location --retry 3 --retry-delay 2 --output "$destination" "$url"
}

info "Preparing sudo access for system-wide software"
if (( EUID != 0 )); then
  sudo -v
fi

info "Installing Mint repository prerequisites and Git"
as_root env DEBIAN_FRONTEND=noninteractive apt-get update
as_root env DEBIAN_FRONTEND=noninteractive apt-get install -y \
  ca-certificates \
  curl \
  git \
  gnupg \
  jq \
  wget

info "Configuring the official NetBird APT repository"
download "$NETBIRD_KEY_URL" "$work_dir/netbird-public.key"
as_root install -d -m 0755 /usr/share/keyrings /etc/apt/sources.list.d
as_root gpg --dearmor --batch --yes \
  --output /usr/share/keyrings/netbird-archive-keyring.gpg \
  "$work_dir/netbird-public.key"
printf 'deb [signed-by=/usr/share/keyrings/netbird-archive-keyring.gpg] %s\n' "$NETBIRD_REPOSITORY" \
  | as_root tee /etc/apt/sources.list.d/netbird.list >/dev/null
as_root env DEBIAN_FRONTEND=noninteractive apt-get update
as_root env DEBIAN_FRONTEND=noninteractive apt-get install -y \
  libgtk-4-1 \
  libwebkitgtk-6.0-4 \
  netbird \
  netbird-ui

info "Installing Google Chrome"
download "$CHROME_DEB_URL" "$work_dir/google-chrome-stable.deb"
as_root env DEBIAN_FRONTEND=noninteractive apt-get install -y "$work_dir/google-chrome-stable.deb"

info "Installing Visual Studio Code"
download "$VSCODE_DEB_URL" "$work_dir/code.deb"
as_root env DEBIAN_FRONTEND=noninteractive apt-get install -y "$work_dir/code.deb"

info "Installing the OpenCode desktop application"
download "$OPENCODE_DESKTOP_DEB_URL" "$work_dir/opencode-desktop.deb"
as_root env DEBIAN_FRONTEND=noninteractive apt-get install -y "$work_dir/opencode-desktop.deb"

info "Configuring managed Figma and WhatsApp Chrome PWAs"
as_root install -d -m 0755 /etc/opt/chrome/policies/managed
as_root tee /etc/opt/chrome/policies/managed/productivity-pwas.json >/dev/null <<'JSON'
{
  "WebAppInstallForceList": [
    {
      "url": "https://www.figma.com/",
      "default_launch_container": "window",
      "create_desktop_shortcut": true
    },
    {
      "url": "https://web.whatsapp.com/",
      "default_launch_container": "window",
      "create_desktop_shortcut": true
    }
  ]
}
JSON
as_root chmod 0644 /etc/opt/chrome/policies/managed/productivity-pwas.json

info "Installing NVM, the latest Node LTS, npm, and the OpenCode CLI for $TARGET_USER"
run_as_target <<USER_SETUP
set -Eeuo pipefail
export NVM_DIR="\$HOME/.nvm"
export PROFILE="\$HOME/.bashrc"
curl -fsSL "https://raw.githubusercontent.com/nvm-sh/nvm/$NVM_VERSION/install.sh" | bash
# shellcheck source=/dev/null
. "\$NVM_DIR/nvm.sh"
nvm install --lts
nvm alias default 'lts/*'
curl -fsSL https://opencode.ai/install | bash
USER_SETUP

info "Verifying installed command-line tools"
as_root netbird version
run_as_target <<'USER_VERIFY'
set -Eeuo pipefail
export NVM_DIR="$HOME/.nvm"
# shellcheck source=/dev/null
. "$NVM_DIR/nvm.sh"
git --version
node --version
npm --version
"$HOME/.opencode/bin/opencode" --version
USER_VERIFY
run_as_target <<'USER_GUI_VERIFY'
set -Eeuo pipefail
code --version
google-chrome-stable --version
USER_GUI_VERIFY

info "Chrome's Figma and WhatsApp PWA policy is installed. On first launch, accept Google's Terms of Service; Chrome will then install both PWAs and their desktop shortcuts automatically."

info "Bootstrap complete. Sign in to NetBird, Figma, and WhatsApp in their respective applications."
