#!/usr/bin/env bash
# Deploy net_alerter and ble_alerter daemons to target host
# Usage: ./deploy-daemon.sh [user@host] [remote-dir-net] [remote-dir-ble]

set -euo pipefail

TARGET_HOST="${1:?Usage: $0 <user@host> [remote-dir-net] [remote-dir-ble]}"
REMOTE_DIR_NET="${2:-/opt/net_alerter}"
REMOTE_DIR_BLE="${3:-/opt/ble_alerter}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

NET_SCRIPT="$SCRIPT_DIR/net_alerter.py"
NET_SERVICE="$SCRIPT_DIR/net_alerter.service"
BLE_SCRIPT="$SCRIPT_DIR/ble_alerter.py"
BLE_SERVICE="$SCRIPT_DIR/ble_alerter.service"

if [[ ! -f "$NET_SCRIPT" ]] || [[ ! -f "$NET_SERVICE" ]] || [[ ! -f "$BLE_SCRIPT" ]] || [[ ! -f "$BLE_SERVICE" ]]; then
    echo "[error] One or more daemon scripts/services not found in $SCRIPT_DIR"
    exit 1
fi

echo "[*] Deploying to $TARGET_HOST..."

# ════════════════════════════════════════════════════════════════════
# NET_ALERTER
# ════════════════════════════════════════════════════════════════════
echo "[*] === NET_ALERTER ==="

# Create directory
ssh "$TARGET_HOST" "mkdir -p $REMOTE_DIR_NET && ls -la $REMOTE_DIR_NET"

# Copy daemon script
echo "[*] Copying net_alerter script..."
scp "$NET_SCRIPT" "$TARGET_HOST:$REMOTE_DIR_NET/net_alerter.py"

# Copy OUI database
echo "[*] Copying OUI database..."
scp "$SCRIPT_DIR/../data/oui.db" "$TARGET_HOST:$REMOTE_DIR_NET/oui.db"

# Copy systemd unit
echo "[*] Copying net_alerter systemd unit..."
scp "$NET_SERVICE" "$TARGET_HOST:/etc/systemd/system/net_alerter.service"

# If .env doesn't exist, create a template
echo "[*] Checking for net_alerter .env..."
ssh "$TARGET_HOST" "
if [[ ! -f $REMOTE_DIR_NET/.env ]]; then
    cat > $REMOTE_DIR_NET/.env <<'EOF'
MATRIX_HOMESERVER=https://your-matrix-homeserver.example.com
MATRIX_ACCESS_TOKEN=
MATRIX_ROOM_ID=
EOF
    chmod 600 $REMOTE_DIR_NET/.env
    echo '[warn] Created .env template - update MATRIX_ACCESS_TOKEN and MATRIX_ROOM_ID'
else
    echo '[ok] .env exists'
fi
"

# Remove old cron if present
echo "[*] Removing old net_alerter cron entries..."
ssh "$TARGET_HOST" "crontab -l 2>/dev/null | grep -v net_alerter | crontab - 2>/dev/null || true"

# Enable and start service
echo "[*] Enabling and starting net_alerter..."
ssh "$TARGET_HOST" "
systemctl daemon-reload
systemctl enable net_alerter
systemctl restart net_alerter
sleep 3
systemctl status net_alerter --no-pager
"

# Verify OUI database
echo "[*] Verifying OUI database on remote host..."
ssh "$TARGET_HOST" "python3 -c \"import sqlite3; c=sqlite3.connect('$REMOTE_DIR_NET/oui.db'); print('OUI rows:', c.execute('SELECT COUNT(*) FROM oui').fetchone()[0])\""

echo "[*] Checking net_alerter logs..."
ssh "$TARGET_HOST" "journalctl -u net_alerter -n 20 --no-pager"

# ════════════════════════════════════════════════════════════════════
# BLE_ALERTER
# ════════════════════════════════════════════════════════════════════
echo ""
echo "[*] === BLE_ALERTER ==="

# Create directory
ssh "$TARGET_HOST" "mkdir -p $REMOTE_DIR_BLE && ls -la $REMOTE_DIR_BLE"

# Copy daemon script
echo "[*] Copying ble_alerter script..."
scp "$BLE_SCRIPT" "$TARGET_HOST:$REMOTE_DIR_BLE/ble_alerter.py"

# Copy systemd unit
echo "[*] Copying ble_alerter systemd unit..."
scp "$BLE_SERVICE" "$TARGET_HOST:/etc/systemd/system/ble_alerter.service"

# If .env doesn't exist, create a template
echo "[*] Checking for ble_alerter .env..."
ssh "$TARGET_HOST" "
if [[ ! -f $REMOTE_DIR_BLE/.env ]]; then
    cat > $REMOTE_DIR_BLE/.env <<'EOF'
MODE=open
KNOWN_DEVICES=
DEPARTURE_TIMEOUT=60
RSSI_MIN=-100
MATRIX_HOMESERVER=https://your-matrix-homeserver.example.com
MATRIX_ACCESS_TOKEN=
MATRIX_ROOM_ID=
LOG_LEVEL=INFO
EOF
    chmod 600 $REMOTE_DIR_BLE/.env
    echo '[warn] Created .env template - update MATRIX_ACCESS_TOKEN and MATRIX_ROOM_ID'
else
    echo '[ok] .env exists'
fi
"

# Install bleak if not present
echo "[*] Checking for python3-bleak..."
ssh "$TARGET_HOST" "
python3 -c 'import bleak' 2>/dev/null && echo '[ok] bleak is installed' || {
    echo '[*] Installing bleak via pip3...'
    pip3 install bleak || {
        apt-get update && apt-get install -y python3-bleak || echo '[warn] Could not install bleak'
    }
}
"

# Enable and start service
echo "[*] Enabling and starting ble_alerter..."
ssh "$TARGET_HOST" "
systemctl daemon-reload
systemctl enable ble_alerter
systemctl restart ble_alerter
sleep 3
systemctl status ble_alerter --no-pager
"

echo "[*] Checking ble_alerter logs..."
ssh "$TARGET_HOST" "journalctl -u ble_alerter -n 20 --no-pager"

# ════════════════════════════════════════════════════════════════════
# DONE
# ════════════════════════════════════════════════════════════════════
echo ""
echo "[done] net_alerter and ble_alerter daemons deployed and running"
