#!/usr/bin/env bash

set -euo pipefail

die() {
  echo "Error: $*" >&2
  exit 1
}

install_type="${INSTALL_TYPE:-gui}"
install_gnome_tray_support="${INSTALL_GNOME_TRAY_SUPPORT:-true}"
repo_version="1.0.8"
repo_filename="protonvpn-stable-release_${repo_version}_all.deb"
repo_url="https://repo.protonvpn.com/debian/dists/stable/main/binary-all/$repo_filename"
repo_sha256="0b14e71586b22e498eb20926c48c7b434b751149b1f2af9902ef1cfe6b03e180"

case "$install_type" in
  cli | gui | both) ;;
  *) die "INSTALL_TYPE must be 'cli', 'gui', or 'both'." ;;
esac
case "$install_gnome_tray_support" in
  true | false) ;;
  *) die "INSTALL_GNOME_TRAY_SUPPORT must be 'true' or 'false'." ;;
esac

command -v apt-get >/dev/null 2>&1 || die "this script requires an APT-based distribution."
if ((EUID == 0)); then
  sudo_cmd=()
elif command -v sudo >/dev/null 2>&1; then
  sudo_cmd=(sudo)
else
  die "run as root or install sudo."
fi

work_dir="$(mktemp -d)"
cleanup() {
  rm -rf -- "$work_dir"
}
trap cleanup EXIT

echo "Installing download prerequisites..."
"${sudo_cmd[@]}" apt-get update
"${sudo_cmd[@]}" apt-get install -y --no-install-recommends ca-certificates curl

echo "Downloading and verifying Proton VPN's repository package..."
curl -fsSL --retry 3 -o "$work_dir/$repo_filename" "$repo_url"
(
  cd "$work_dir"
  printf '%s  %s\n' "$repo_sha256" "$repo_filename" | sha256sum --check -
)

echo "Installing the Proton VPN repository..."
if ! "${sudo_cmd[@]}" dpkg -i "$work_dir/$repo_filename"; then
  "${sudo_cmd[@]}" apt-get install -f -y
  "${sudo_cmd[@]}" dpkg -i "$work_dir/$repo_filename"
fi
"${sudo_cmd[@]}" apt-get update

packages=()
case "$install_type" in
  cli) packages=(proton-vpn-cli) ;;
  gui) packages=(proton-vpn-gnome-desktop) ;;
  both)
    packages=(proton-vpn-cli proton-vpn-gnome-desktop)
    echo "Note: Proton VPN's GUI and CLI cannot be used at the same time."
    ;;
esac

echo "Installing ${packages[*]}..."
"${sudo_cmd[@]}" apt-get install -y "${packages[@]}"

if [[ "$install_gnome_tray_support" == true && "$install_type" != cli ]]; then
  echo "Installing optional GNOME tray support..."
  "${sudo_cmd[@]}" apt-get install -y \
    gnome-shell-extension-appindicator gnome-shell-extension-prefs
fi

echo "Proton VPN installation completed successfully."
if [[ "$install_type" == cli || "$install_type" == both ]]; then
  echo "Run 'protonvpn --help' to get started with the CLI."
fi
