#!/usr/bin/env bash
set -e

INSTALL_DIR="/opt/granus"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'

NC='\033[0m' # No Color

function cancelInstallation {
  if [ -f "$INSTALL_DIR/license_key.new" ]; then
    rm "$INSTALL_DIR/license_key.new"
  fi
  if [ -f "$INSTALL_DIR/installed_components.new" ]; then
    rm "$INSTALL_DIR/installed_components.new"
  fi
  clear
  echo -e "${RED}Installation cancelled${NC}"
  exit
}

# Change working directory to script directory
cd "$(dirname "$(readlink -f "$0")")"

# Check if installer is running as root
if [ "$EUID" -ne 0 ]; then
  echo "This installation script must be run as root (sudo ./install.sh)" >&2 
  exit 1
fi

# Detect OS
OS=""
if type lsb_release >/dev/null 2>&1; then
  OS=$(lsb_release -si)
elif [ -f /etc/os-release ]; then
  . /etc/os-release
  OS=$NAME
else
  echo "Unsupported OS"
  exit 1
fi
echo "Detected OS: $OS"

# Detect package manager
PM=""
case "$OS" in
  "Ubuntu" | "Debian GNU/Linux")
    PM="apt"
    ;;
  "Fedora" | "CentOS Linux" | "Rocky Linux")
    PM="dnf"
    ;;
  "Arch Linux")
    PM="pacman"
    ;;
  *)
    echo "Unsupported OS"
    exit 1
    ;;
esac
echo "Detected package manager: $PM"

# Detect architecture
ARCH=$(uname -m)
if [[ ! "$(uname -m)" =~ ^(aarch64|x86_64)$ ]]; then
  echo "Unsupported architecture $ARCH"
  exit 1
fi
echo "Detected architecture: $ARCH"

# Check if dialog is installed
if ! [ -x "$(command -v dialog)" ]; then
    echo "Installing dependencies"
    if [ "$PM" == "apt" ]; then
        apt update
        apt install -y dialog 
    elif [ "$PM" == "dnf" ]; then
        dnf update
        dnf install -y dialog
    elif [ "$PM" == "pacman" ]; then
        pacman -S --noconfirm dialog
    fi
fi
if ! [ -x "$(command -v dialog)" ]; then
    echo "Dialog installation failed / dialog not available"
    exit
fi

# Ask to continue with installation (default No)
dialog \
  --backtitle "Granus - DPSystem Installer" \
  --defaultno \
  --yesno "This script will install the server. Do you want to continue?" 7 60 \
  || cancelInstallation

# Create installation directory
mkdir -p $INSTALL_DIR
if [ $? -ne 0 ]; then
  echo "Failed to create installation directory $INSTALL_DIR" >&2
  exit 1
fi

# Select components to install
COMPONENT_DPSERVICE_EDOKLADY_CZ=OFF
COMPONENT_DPSERVICE_ADDRESS=OFF
if [ -f $INSTALL_DIR/installed_components.txt ]; then
  if grep -q "DPService-eDoklady-CZ" $INSTALL_DIR/installed_components.txt; then
    COMPONENT_DPSERVICE_EDOKLADY_CZ=ON
  fi
  if grep -q "DPService-Address" $INSTALL_DIR/installed_components.txt; then
    COMPONENT_DPSERVICE_ADDRESS=ON
  fi
else
  # Default selection
  COMPONENT_DPSERVICE_EDOKLADY_CZ=ON
fi
dialog \
  --backtitle "Granus - DPSystem Installer" \
  --checklist "Select components to install" 10 60 3 \
  "DPService-eDoklady-CZ" "" $COMPONENT_DPSERVICE_EDOKLADY_CZ \
  "DPService-Address" "Not available" $COMPONENT_DPSERVICE_ADDRESS \
  2> $INSTALL_DIR/installed_components.new \
  || cancelInstallation
mv $INSTALL_DIR/installed_components.new $INSTALL_DIR/installed_components.txt
chmod 600 $INSTALL_DIR/installed_components.txt
if grep -q "DPService-eDoklady-CZ" $INSTALL_DIR/installed_components.txt; then
  COMPONENT_DPSERVICE_EDOKLADY_CZ=ON
fi
if grep -q "DPService-Address" $INSTALL_DIR/installed_components.txt; then
  COMPONENT_DPSERVICE_ADDRESS=ON
fi


# Ask for license key
LICENSE_KEY=""
if [ -f $INSTALL_DIR/license_key.txt ]; then
  LICENSE_KEY=$(cat $INSTALL_DIR/license_key.txt)
fi
dialog \
  --backtitle "Granus - DPSystem Installer" \
  --inputbox "Enter license key" 8 60 "$LICENSE_KEY" \
  2> $INSTALL_DIR/license_key.new \
  || cancelInstallation
mv $INSTALL_DIR/license_key.new $INSTALL_DIR/license_key.txt
chmod 600 $INSTALL_DIR/license_key.txt
LICENSE_KEY=$(cat $INSTALL_DIR/license_key.txt)

##############################################################################
##############################################################################
##############################################################################

clear

# Install DPSystem
echo -e "${YELLOW}Installing DPSystem base${NC}"
cp DPSystem_version.txt $INSTALL_DIR
tar -xvf DPSystem.tar -C $INSTALL_DIR --strip-components=1 "$ARCH/" \
  | sed 's/^/ * /'
echo

echo -e "${YELLOW}Registering license${NC}"
if [ ! -z "$LICENSE_KEY" ]; then
  $INSTALL_DIR/sbin/register -license "$LICENSE_KEY"
fi
echo

# Install components - DPService-eDoklady-CZ
if [ "$COMPONENT_DPSERVICE_EDOKLADY_CZ" == "ON" ]; then
  echo -e "${YELLOW}Installing DPService-eDoklady-CZ${NC}"

  SERVICE_INSTALLED=0
  if systemctl list-unit-files | grep -qw "DPService-eDoklady-CZ.service"; then
    SERVICE_INSTALLED=1
    echo -n "Stopping DPService-eDoklady-CZ service"
    systemctl stop DPService-eDoklady-CZ.service
    echo -e " - ${GREEN}OK${NC}"
  fi

  echo "Extracting files"
  tar -xvf DPService-eDoklady-CZ.tar -C $INSTALL_DIR --strip-components=1 "$ARCH/" "all/" \
    | sed 's/^/ * /'
  cp $INSTALL_DIR/var/template/translateNationality-Code3.json $INSTALL_DIR/var/translateNationality.json
  cp $INSTALL_DIR/var/template/translateSex.json $INSTALL_DIR/var/translateSex.json
  mkdir -p $INSTALL_DIR/lib/certs
  chmod 700 $INSTALL_DIR/lib/certs

  if [ "$SERVICE_INSTALLED" -eq 0 ]; then
    echo "Installing DPService-eDoklady-CZ service"
    $INSTALL_DIR/bin/DPService-eDoklady-CZ -service install
  fi
  echo -n "Starting DPService-eDoklady-CZ service"
  systemctl start DPService-eDoklady-CZ.service
  echo -e " - ${GREEN}OK${NC}"
  echo
fi

# Install components - DPService-Address
if [ "$COMPONENT_DPSERVICE_ADDRESS" == "ON" ]; then
  echo -e "${YELLOW}Installing DPService-Address${NC}"
  echo "Not available"
  echo
fi

echo -e "${GREEN}Installation completed${NC}"