#!/bin/bash
# deckpad installer for Steam Deck / any systemd Linux. Runs as your normal user.
#   install.sh           install (or update) and start it as a background service
#   install.sh --udev    also add a udev rule so /dev/uinput is writable (needs sudo)
#   install.sh --remove  stop and remove it
set -e
BASE=${DECKPAD_URL:-https://goldartfrog.net/deckpad}
DIR=$HOME/.local/share/deckpad
UNIT=$HOME/.config/systemd/user/deckpad.service

if [ "$1" = --remove ]; then
  systemctl --user disable --now deckpad 2>/dev/null || true
  rm -f "$UNIT"; rm -rf "$DIR"; systemctl --user daemon-reload
  echo "deckpad removed (join code kept in ~/.config/deckpad)"; exit 0
fi

if [ "$1" = --udev ]; then
  # same rule Steam's own steam-devices package uses: the logged-in user gets uinput
  echo 'KERNEL=="uinput", SUBSYSTEM=="misc", TAG+="uaccess", OPTIONS+="static_node=uinput"' |
    sudo tee /etc/udev/rules.d/60-deckpad-uinput.rules >/dev/null
  sudo udevadm control --reload && sudo udevadm trigger --name-match=uinput || true
  sudo setfacl -m "u:$USER:rw" /dev/uinput 2>/dev/null || true
fi

mkdir -p "$DIR" "$(dirname "$UNIT")"
SRC=$(cd "$(dirname "$0")" 2>/dev/null && pwd)
if [ -f "$SRC/deckpad.py" ] && [ -f "$SRC/pad.html" ]; then
  cp "$SRC/deckpad.py" "$SRC/pad.html" "$DIR/"
else
  curl -fsSL "$BASE/deckpad.py" -o "$DIR/deckpad.py"
  curl -fsSL "$BASE/pad.html" -o "$DIR/pad.html"
  curl -fsSL "$BASE/install.sh" -o "$DIR/install.sh"
fi
[ -f "$SRC/install.sh" ] && [ "$SRC" != "$DIR" ] && cp "$SRC/install.sh" "$DIR/" || true
chmod +x "$DIR/deckpad.py" "$DIR/install.sh" 2>/dev/null || true

if [ ! -w /dev/uinput ]; then
  echo "!! Your user can't write /dev/uinput, so controllers can't be created yet."
  echo "   Fix once (Steam Deck: run 'passwd' first if you never set a password):"
  echo "     bash $DIR/install.sh --udev"
fi

cat > "$UNIT" <<EOF
[Unit]
Description=deckpad - phones as game controllers

[Service]
ExecStart=/usr/bin/python3 $DIR/deckpad.py
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target
EOF
systemctl --user daemon-reload
systemctl --user enable deckpad >/dev/null 2>&1
systemctl --user restart deckpad
sleep 1
if systemctl --user is-active --quiet deckpad; then
  echo "deckpad is running and will start on every boot (Game Mode too)."
else
  echo "deckpad failed to start; see: journalctl --user -u deckpad -n 20"
fi
IP=$(python3 -c "import socket;s=socket.socket(2,2);s.connect(('10.255.255.255',1));print(s.getsockname()[0])" 2>/dev/null || echo "<deck-ip>")
echo "On each phone (same Wi-Fi), open:  http://$IP:8777"
echo "Join code: $(cat ~/.config/deckpad/code 2>/dev/null || echo '(created on first start)')"
