#!/usr/bin/env bash
set -euo pipefail

service_name="fsrdp-server"
service_user="fsrdp-server"
install_directory="/opt/fsrdp-server"
data_directory="${install_directory}/data"
configuration_directory="/etc/fsrdp-server"
script_directory="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
start_service=false

if [[ "${1:-}" == "--start" ]]; then
  start_service=true
elif [[ $# -ne 0 ]]; then
  echo "Usage: sudo ./install.sh [--start]" >&2
  exit 2
fi

if [[ $EUID -ne 0 ]]; then
  echo "This installer must be run as root." >&2
  exit 1
fi

if [[ ! -x "${script_directory}/FsRdpServer" ]]; then
  echo "FsRdpServer was not found beside install.sh." >&2
  exit 1
fi

if ! getent group "${service_user}" >/dev/null; then
  groupadd --system "${service_user}"
fi

if ! id --user "${service_user}" >/dev/null 2>&1; then
  useradd \
    --system \
    --gid "${service_user}" \
    --home-dir "${data_directory}" \
    --shell /usr/sbin/nologin \
    "${service_user}"
fi

install -d -o root -g root -m 0755 "${install_directory}"
install -d -o "${service_user}" -g "${service_user}" -m 0750 "${data_directory}"
install -d -o "${service_user}" -g "${service_user}" -m 0750 "${data_directory}/Logs"
install -d -o root -g root -m 0755 "${configuration_directory}"

was_active=false
if systemctl is-active --quiet "${service_name}.service"; then
  was_active=true
  systemctl stop "${service_name}.service"
fi

install -o root -g root -m 0755 \
  "${script_directory}/FsRdpServer" \
  "${install_directory}/FsRdpServer"
install -o root -g root -m 0644 \
  "${script_directory}/fsrdp-server.service" \
  "/etc/systemd/system/${service_name}.service"

if [[ ! -f "${data_directory}/appsettings.json" ]]; then
  install -o "${service_user}" -g "${service_user}" -m 0640 \
    "${script_directory}/appsettings.example.json" \
    "${data_directory}/appsettings.json"
fi

if [[ ! -f "${configuration_directory}/fsrdp-server.env" ]]; then
  install -o root -g root -m 0600 \
    "${script_directory}/fsrdp-server.env.example" \
    "${configuration_directory}/fsrdp-server.env"
fi

systemctl daemon-reload
systemctl enable "${service_name}.service"

if $start_service || $was_active; then
  systemctl start "${service_name}.service"
fi

echo "FsRdpServer installed in ${install_directory}."
echo "Persistent data remains in ${data_directory} during updates."
if ! $start_service && ! $was_active; then
  echo "Install the certificate and license, set the PFX password, then run:"
  echo "  sudo systemctl start ${service_name}.service"
fi
