#!/bin/bash
# Install script for presence daemon
# Deploys sensor.py and service configuration to /opt/sensor/

set -e

echo "Installing presence daemon..."

# Create sensor directory
sudo mkdir -p /opt/sensor
sudo chown $USER:$USER /opt/sensor

# Copy daemon and schema
cp presence_daemon.py /opt/sensor/sensor.py
cp presence_schema.sql /opt/sensor/
chmod +x /opt/sensor/sensor.py

echo "Created /opt/sensor/sensor.py and schema"

# Create systemd service
sudo tee /etc/systemd/system/sensor.service > /dev/null << 'EOF'
[Unit]
Description=Network Sensor
After=network.target

[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/sensor/sensor.py
Restart=on-failure
RestartSec=10
Environment=PRESENCE_DB_PATH=/opt/sensor/presence.db
# Optional: override default status port (9191)
# Environment=PRESENCE_STATUS_PORT=9191
# Optional: configure Matrix webhook for alerts
# Environment=PRESENCE_MATRIX_WEBHOOK=https://matrix.example.com/hook

[Install]
WantedBy=multi-user.target
EOF

echo "Created /etc/systemd/system/sensor.service"

# Reload systemd and enable service
sudo systemctl daemon-reload
sudo systemctl enable sensor
sudo systemctl start sensor

echo "Enabled and started sensor service"
echo "Status:"
sudo systemctl status sensor --no-pager | head -20
