#!/usr/bin/env bash

##
# installs systemd files to keep NOSE running on your NOSEputer

set -euo pipefail

quiet() { "$@" > /dev/null 2>&1; }

SYSTEMD_DIR="/etc/systemd/system"
SERVICE_NAME="nose-pluto"
SERVICE_FILE="$(dirname "$0")/${SERVICE_NAME}.service"
SYSTEMD_PATH="${SYSTEMD_DIR}/${SERVICE_NAME}.service"

REBOOT_NAME="nose-reboot"
REBOOT_FILE="$(dirname "$0")/${REBOOT_NAME}.service"
REBOOT_PATH="${SYSTEMD_DIR}/${REBOOT_NAME}.service"

POLKIT_NAME="49-nose-reboot"
POLKIT_FILE="$(dirname "$0")/${POLKIT_NAME}.rules"
POLKIT_PATH="/etc/polkit-1/rules.d/${POLKIT_NAME}.rules"

BUN_SYMLINK="/usr/local/bin/bun"
BUN_REAL="$HOME/.bun/bin/bun"

echo ">> Updating system libraries"
quiet sudo apt-get update
quiet sudo apt-get install -y libcap2-bin
quiet sudo apt-get install -y avahi-utils

echo ">> Ensuring bun is available in /usr/local/bin"
if [ ! -x "$BUN_SYMLINK" ]; then
  if [ -x "$BUN_REAL" ]; then
    quiet sudo ln -sf "$BUN_REAL" "$BUN_SYMLINK"
    echo "Symlinked $BUN_REAL -> $BUN_SYMLINK"
  else
    echo ">> Installing bun at $BUN_REAL"
    quiet sudo apt install unzip
    quiet curl -fsSL https://bun.com/install | bash
    quiet sudo ln -sf "$BUN_REAL" "$BUN_SYMLINK"
    echo "Symlinked $BUN_REAL -> $BUN_SYMLINK"
  fi
else
  echo "bun already available at $BUN_SYMLINK"
fi

echo ">> Setting CAP_NET_BIND_SERVICE on $BUN_REAL"
quiet sudo setcap 'cap_net_bind_service=+ep' "$BUN_REAL"
quiet /usr/sbin/getcap "$BUN_REAL" || true

echo ">> Installing main NOSE Pluto service"
quiet sudo install -m 644 -o root -g root "$SERVICE_FILE" "$SYSTEMD_PATH"

echo ">> Installing NOSE reboot helper service"
quiet sudo install -m 644 -o root -g root "$REBOOT_FILE" "$REBOOT_PATH"

echo ">> Installing PolicyKit rule"
quiet sudo install -m 644 -o root -g root "$POLKIT_FILE" "$POLKIT_PATH"

echo ">> Reloading systemd daemon"
quiet sudo systemctl daemon-reload

echo ">> Reloading polkit daemon"
quiet sudo systemctl restart polkit || true

echo ">> Enabling $SERVICE_NAME to start at boot"
quiet sudo systemctl enable "$SERVICE_NAME"

echo ">> Starting (or restarting) $SERVICE_NAME"
quiet sudo systemctl restart "$SERVICE_NAME"

echo ">> Enabling kiosk mode"
quiet mkdir -p ~/.config/labwc
cat > ~/.config/labwc/autostart <<'EOF'
chromium-browser --noerrdialogs --disable-infobars --kiosk http://localhost
EOF

echo ">> Done! Rebooting!"
quiet systemctl status "$SERVICE_NAME" --no-pager -l
quiet sudo nohup reboot >/dev/null 2>&1 &
exit 0
