#!/usr/bin/env bash
# Installs the overdeck-web and overdeck-web-watchdog systemd --user units, plus the
# watchdog binary. Does NOT enable or start them — that is an explicit separate step.
set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
web_dir="$(cd "${script_dir}/../apps/web" && pwd)"
deploy_dir="${OVERDECK_DEPLOY_DIR:-$HOME/.local/share/overdeck/deploy}"
pages_dir="${web_dir}/src/pages"
bin_dir="${HOME}/.local/bin"
watchdog_bin="${bin_dir}/overdeck-web-watchdog"
release_bin="${bin_dir}/overdeck-web-release"
release_current="${web_dir}/.releases/current"
unit_dest_dir="${HOME}/.config/systemd/user"

# the systemd unit runs outside the interactive PATH, so a shell shim on PATH is not a
# valid ExecStart; prefer the system interpreter and fall back only if it is absent.
if [[ -x /usr/bin/node ]]; then
  node_bin=/usr/bin/node
else
  node_bin="$(command -v node || true)"
fi
if [[ -z "${node_bin}" ]]; then
  echo "error: node is not on PATH — install node before running this script" >&2
  exit 1
fi

if [[ ! -d "${pages_dir}" ]]; then
  echo "error: ${pages_dir} not found — is the repo checkout intact?" >&2
  exit 1
fi

web_unit="$(sed \
  -e "s#__WEB_DIR__#${web_dir}#g" \
  -e "s#__WEB_RELEASE_CURRENT__#${release_current}#g" \
  -e "s#__NODE_BIN__#${node_bin}#g" \
  "${script_dir}/overdeck-web.service")"

watchdog_unit="$(sed \
  -e "s#__WATCHDOG_BIN__#${watchdog_bin}#g" \
  -e "s#__PAGES_DIR__#${pages_dir}#g" \
  "${script_dir}/overdeck-web-watchdog.service")"

if [[ "${OVERDECK_INSTALL_WEB_DRY_RUN:-}" == "1" ]]; then
  printf 'unit:overdeck-web.service\n%s\n' "${web_unit}"
  printf 'unit:overdeck-web-watchdog.service\n%s\n' "${watchdog_unit}"
  printf 'bin:%s\n' "${watchdog_bin}"
  printf 'bin:%s\n' "${release_bin}"
  exit 0
fi

# The rendered unit pins ExecStart, WorkingDirectory and the probe's pages dir to this
# checkout. Installing from a dev tree would point the live service at unlanded code.
if [[ "${script_dir}" != "$(cd "${deploy_dir}" 2>/dev/null && pwd)/packaging" ]]; then
  echo "error: refusing to install from ${script_dir} — units may only be rendered from the deploy clone ${deploy_dir}" >&2
  echo "       deploy with: bash ${deploy_dir}/packaging/deploy-local.sh" >&2
  exit 1
fi

mkdir -p "${unit_dest_dir}" "${bin_dir}"
install -m 755 "${script_dir}/web-watchdog.sh" "${watchdog_bin}"
install -m 755 "${script_dir}/web-release.sh" "${release_bin}"
printf '%s\n' "${web_unit}" > "${unit_dest_dir}/overdeck-web.service"
printf '%s\n' "${watchdog_unit}" > "${unit_dest_dir}/overdeck-web-watchdog.service"

systemctl --user daemon-reload

echo "Installed ${unit_dest_dir}/overdeck-web.service"
echo "Installed ${unit_dest_dir}/overdeck-web-watchdog.service"
echo "Installed ${watchdog_bin}"
echo "Installed ${release_bin}"
echo "Not enabled and not started. To run them:"
echo "  systemctl --user enable --now overdeck-web.service overdeck-web-watchdog.service"
