#===========================================================================
#  ____                _            ___
# |  _ \              | |          / _ \
# | |_) | ___  _ __ __| | ___ _ __| | | |
# |  _ < / _ \| '__/ _` |/ _ \ '__| | | |
# | |_) | (_) | | | (_| |  __/ |  | |_| |
# |____/ \___/|_|  \__,_|\___|_|   \___/
#
#===========================================================================
# Device & Desktop App Installation Script
# Version: 0.1.4 Update 12/30/2025
# Border0 <support@border0.com>
#===========================================================================

#!/bin/bash
set -euo pipefail

# Color and style definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
RESET='\033[0m'

# Emoji definitions
CHECK_MARK='✅'
CROSS_MARK='❌'
WARNING_SIGN='⚠️'
INFO_SIGN='ℹ️'
SCRIPT_EXEC_USER=$(whoami)
ORIGINAL_HOME="$HOME"

# Function to check for root privileges
check_root() {
  if [[ "$UID" -ne 0 ]]; then
    echo -e "${BLUE}${INFO_SIGN} Running with regular user privileges${RESET}"
    IS_ROOT=false
  else
    echo -e "${BLUE}${INFO_SIGN} Running as root${RESET}"
    IS_ROOT=true
  fi
}

# Function to detect the package manager
detect_package_manager() {
  local pkg_mgmt="unsupported"
  echo -e "${BLUE}${INFO_SIGN} Detecting package manager...${RESET}"
  if [[ -e /etc/os-release ]]; then
    source /etc/os-release
    case "$ID" in
    ubuntu | debian) pkg_mgmt="apt-get" ;;
    centos | rhel | amzn) pkg_mgmt="yum" ;;
    esac
  fi
  echo "$pkg_mgmt"
}

# Function to detect system architecture
detect_architecture() {
  local hw_machine
  hw_machine=$(uname -m)
  case "$hw_machine" in
  x86_64) echo "linux_amd64" ;;
  aarch64 | arm64) echo "linux_arm64" ;;
  armv7l) echo "linux_arm" ;;
  *) echo "linux_amd64" ;;
  esac
}

# Function to install the Border0 CLI tool
install_border0_cli() {
  local arch="$1"
  local install_cmd="curl -sSL"

  if [[ "$UID" -ne 0 ]]; then
    install_cmd="sudo $install_cmd"
    echo -e "${BLUE}${INFO_SIGN} Running with sudo${RESET}"
  fi

  if [[ -e /usr/local/bin/border0 ]]; then
    echo -e "${GREEN}${CHECK_MARK} Border0 CLI tool is already installed.${RESET}"
    echo -e "${BLUE}${INFO_SIGN} Checking for updates...${RESET}"
    if [[ "$UID" -ne 0 ]]; then
      sudo border0 version upgrade
    else
      border0 version upgrade
    fi
  else
    echo -e "${BLUE}${INFO_SIGN} Installing Border0 CLI tool...${RESET}"
    $install_cmd "https://download.border0.com/${arch}/border0" -o /usr/local/bin/border0
    if [[ "$UID" -ne 0 ]]; then
      sudo chmod +x /usr/local/bin/border0
    else
      chmod +x /usr/local/bin/border0
    fi
    echo -e "${GREEN}${CHECK_MARK} Border0 CLI tool installed successfully.${RESET}"
  fi
}

# Function to install the Border0 systemd service
install_systemd_service() {
  if [[ -e /etc/systemd/system/border0-device.service ]]; then
    echo -e "${GREEN}${CHECK_MARK} Border0 systemd service is already installed.${RESET}"
  else
    echo -e "${BLUE}${INFO_SIGN} Installing Border0 Client Device systemd service...${RESET}"
    if [[ "$UID" -ne 0 ]]; then
      sudo border0 node install --start-vpn --home-dir "$ORIGINAL_HOME"
      sudo systemctl daemon-reload
    else
      border0 node install --start-vpn
      systemctl daemon-reload
    fi
    echo -e "${GREEN}${CHECK_MARK} Border0 device service installed successfully!${RESET}"
  fi

  echo -e "${BLUE}${INFO_SIGN} Starting Border0 Client Device service...${RESET}"
  if [[ "$UID" -ne 0 ]]; then
    sudo systemctl start --no-block border0-device.service
  else
    systemctl start --no-block border0-device.service
  fi
  echo -e "${GREEN}${CHECK_MARK} Border0 device service started successfully!${RESET}"
}

# Function to prompt for organization subdomain and handle login
prompt_org_subdomain() {
  local org_subdomain
  for i in {1..3}; do
    echo -ne "${BLUE}${INFO_SIGN} Enter your org subdomain: ${RESET}"
    read org_subdomain

    if [[ -z "$org_subdomain" ]]; then
      echo -e "${RED}${CROSS_MARK} Org subdomain cannot be empty. Please try again.${RESET}"
      continue
    fi
    if [[ ! "$org_subdomain" =~ ^[a-z0-9-]+$ ]]; then
      echo -e "${RED}${CROSS_MARK} Invalid subdomain format. Only lowercase letters, numbers, and dashes are allowed.${RESET}"
      continue
    fi

    echo -ne "${BLUE}${INFO_SIGN} You entered '${org_subdomain}'. Is this correct? (y/n): ${RESET}"
    read confirm

    if [[ "$confirm" =~ ^[Yy]$ ]]; then
      echo -e "${BLUE}${INFO_SIGN} Logging in...${RESET}"
      # check the user that ran the script
      if [[ "$SCRIPT_EXEC_USER" != "root" ]]; then
        # change the owner of the ~/.border0 directory to the user that ran the script
        # Only chown if the directory exists (may not exist yet on first login)
        if [[ -d "$ORIGINAL_HOME/.border0" ]]; then
          sudo chown -R "$SCRIPT_EXEC_USER" "$ORIGINAL_HOME/.border0"
        fi
      fi
      # login to the org
      if border0 client login --org "$org_subdomain"; then
        echo -e "${GREEN}${CHECK_MARK} Login successful!${RESET}"
        return 0
      else
        echo -e "${RED}${CROSS_MARK} Login failed. Please check your org subdomain and try again.${RESET}"
      fi
    else
      echo -e "${YELLOW}${WARNING_SIGN} Please re-enter your org subdomain.${RESET}"
    fi
  done
  return 1
}

# Function to prompt user to start the VPN
start_vpn_prompt() {
  echo -ne "${BLUE}${INFO_SIGN} Would you like to start the Border0 VPN now? (y/n): ${RESET}"
  read response

  case "$response" in
  [Yy]*)
    echo -e "${GREEN}${CHECK_MARK} Starting Border0 VPN...${RESET}"
    echo -e "${BLUE}${INFO_SIGN} Running: border0 node vpn start${RESET}"
    echo -e "${BLUE}${INFO_SIGN} You can stop the VPN with: border0 node vpn stop${RESET}"
    border0 node vpn start 2>&1 >/dev/null &
    ;;
  *)
    echo -e "${YELLOW}${WARNING_SIGN} You can start the Border0 VPN later by running: border0 node vpn start${RESET}"
    ;;
  esac
}

# Main script execution
main() {
  IS_ROOT=true
  check_root

  local pkg_mgmt
  pkg_mgmt=$(detect_package_manager)
  if [[ "$pkg_mgmt" == "unsupported" ]]; then
    echo -e "${RED}${CROSS_MARK} Unsupported package manager. Exiting.${RESET}"
    exit 1
  fi

  local arch
  arch=$(detect_architecture)

  install_border0_cli "$arch"
  install_systemd_service

  echo -e "${BLUE}${INFO_SIGN} Please select the Border0 organization to log in to.${RESET}"
  echo -e "${BLUE}${INFO_SIGN} You can find it in the top left corner of the Border0 dashboard: https://portal.border0.com/dashboard${RESET}"

  if prompt_org_subdomain; then
    echo -e "${BLUE}${INFO_SIGN} Restarting systemd border0-device service...${RESET}"
    if [[ "$UID" -ne 0 ]]; then
      sudo systemctl restart border0-device.service
    else
      systemctl restart border0-device.service
    fi
    echo -e "${GREEN}${CHECK_MARK} Your Border0 Client Device service is installed.${RESET}\n"

    start_vpn_prompt
  fi
}

main
