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

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

if [ "$EUID" -ne 0 ]; then
  echo "Please run as root"
  exit 1
fi

init_process=$(ps -p 1 -o comm=) || error_exit
if [ "$init_process" = "systemd" ]; then
    echo "This system uses Systemd."
else
    echo "This system does not use Systemd."
    exit 1
fi

required_commands=("jq" "curl" "wget")

for cmd in "${required_commands[@]}"; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
        missing_commands+=("$cmd")
    fi
done

if [ ${#missing_commands[@]} -ne 0 ]; then
    echo "Error: The following commands were not found. Operation will be terminated."
    for cmd in "${missing_commands[@]}"; do
        echo " - $cmd"
    done
    exit 1
fi

read -p "Hostname configuration (If left blank, the default hostname will be used.): " hostname < /dev/tty

installation() {
    INSTALL_PATH=/usr/local/bin/
    FILE_NAME=pcsc-rs
    VERSION=$(curl -fsSL https://api.github.com/repos/eoeo-org/pcsc-rs/releases/latest | jq -r ".tag_name")
    ARCH=$(uname -m)
    DOWNLOAD_URL="https://github.com/eoeo-org/pcsc-rs/releases/latest/download/pcsc-rs-$VERSION-$ARCH-unknown-linux-gnu"

    if [ -n "$hostname" ]; then
      HOSTNAME_ENV="Environment=HOSTNAME=$hostname"
    else
      HOSTNAME_ENV=""
    fi

    echo "Downloading latest binary..."
    downnload_process=$(wget "$DOWNLOAD_URL" -O "$INSTALL_PATH$FILE_NAME") || error_exit

    echo "Download done, Setting Permission..."
    chmod +x "$INSTALL_PATH$FILE_NAME"

    echo "Set Permission done, Set Systemctl..."
    cat <<EOF > /etc/systemd/system/pcsc-rs.service
[Unit]
Description=PCStatus Client
After=network-online.target

[Service]
Environment=PASS=npU7pmkkYfuUdKfqzm2BtDfBPEe4pizrXyPVj8Fby3KaUtehNu3ToDtM8uEdGBr3AS9LRUkZixtZxuKTvsL2e4BVrfzWWG7RqqVThLWsVLHLaJJ8ekeGuHtLBkfZpBtv
Environment="PCSC_UPDATED=terminate"
$HOSTNAME_ENV
ExecStart=/usr/local/bin/pcsc-rs
Restart=always

[Install]
WantedBy=network-online.target
EOF
    systemctl daemon-reload
    systemctl enable --now pcsc-rs

    echo "Install done!"
}

read -p "Are you sure you want to proceed with the installation? (y/n): " answer < /dev/tty

case "${answer,,}" in
  y|yes)
    installation
    ;;
  n|no|"")
    echo "Installation aborted."
    exit 0
    ;;
  *)
    echo "Invalid input. Installation aborted."
    exit 1
    ;;
esac
