#!/usr/bin/env bash
# Install POG-CC PermDevMapper: udev /dev/ser_DT1 + systemd mapper → /dev/pogcc.
#
#   cd ~/DyzineFrame && bash install_pogcc_permdev.sh
#
# udev matches FTDI VID:PID 0403:6001 only. Never a cable serial number.
# Idempotent. Does not start/stop DyzineFrame. Cable need not be plugged
# to install the rule (symlink appears when the FTDI enumerates).

set -euo pipefail

if [[ "${EUID}" -eq 0 ]]; then
  echo "DO NOT RUN THIS SCRIPT AS ROOT (uses sudo)!" >&2
  exit 1
fi

DF="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RULES_IN="${DF}/udev/99-pogcc-ser-dt1.rules.in"
RULES_DST="/etc/udev/rules.d/99-pogcc-ser-dt1.rules"
UNIT_SRC="${DF}/pogcc-permdev.service"
UNIT_DST="/etc/systemd/system/pogcc-permdev.service"
MAPPER="${DF}/pogcc_permdev_mapper.py"

if [[ ! -f "${RULES_IN}" ]]; then
  echo "FATAL: missing ${RULES_IN}" >&2
  exit 1
fi
if [[ ! -f "${MAPPER}" ]]; then
  echo "FATAL: missing ${MAPPER}" >&2
  exit 1
fi
if [[ ! -f "${UNIT_SRC}" ]]; then
  echo "FATAL: missing ${UNIT_SRC}" >&2
  exit 1
fi

if grep -q 'ENV{ID_SERIAL_SHORT}' "${RULES_IN}"; then
  echo "FATAL: ${RULES_IN} still matches ENV{ID_SERIAL_SHORT} — P3 udev must be VID:PID only." >&2
  exit 1
fi

echo "=== POG-CC PermDevMapper install ==="
echo "tree: ${DF}"
echo "udev: FTDI 0403:6001 → /dev/ser_DT1 (no serial)"

sudo install -m 644 "${RULES_IN}" "${RULES_DST}"

# Point unit at this tree's mapper (home may not be /home/topbox on odd benches).
TMP_UNIT="$(mktemp)"
sed "s|/home/topbox/DyzineFrame/pogcc_permdev_mapper.py|${MAPPER}|g" "${UNIT_SRC}" > "${TMP_UNIT}"
sudo install -m 644 "${TMP_UNIT}" "${UNIT_DST}"
rm -f "${TMP_UNIT}"

chmod +x "${MAPPER}" || true
sudo mkdir -p /run/dyzineframe
sudo udevadm control --reload-rules
sudo udevadm trigger --subsystem-match=tty --action=add || true

sudo systemctl daemon-reload
sudo systemctl enable pogcc-permdev.service
sudo systemctl restart pogcc-permdev.service

sleep 0.5
echo ""
echo "status:"
systemctl is-active pogcc-permdev.service || true
ls -l /dev/ser_DT1 /dev/pogcc 2>/dev/null || true
if [[ -f /run/dyzineframe/pogcc_link.status ]]; then
  echo -n "link: "
  cat /run/dyzineframe/pogcc_link.status
  echo
fi
echo ""
echo "POG-CC PermDevMapper install complete."
echo "  DyzineFrame / ethergold-pogcc-com should open /dev/pogcc (not /dev/ttyUSB0)."
