#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
USER_NAME="$(whoami)"

echo "🔧 Setting up Weather Station..."

# ── InfluxDB ──────────────────────────────────────────────────────────────────

if ! command -v influxd &> /dev/null; then
    echo "📦 Installing InfluxDB..."
    curl https://repos.influxdata.com/influxdata-archive.key | gpg --dearmor | sudo tee /usr/share/keyrings/influxdata-archive-keyring.gpg > /dev/null
    echo "deb [signed-by=/usr/share/keyrings/influxdata-archive-keyring.gpg] https://repos.influxdata.com/debian stable main" | sudo tee /etc/apt/sources.list.d/influxdata.list
    sudo apt update && sudo apt install -y influxdb2
    sudo systemctl enable --now influxdb
else
    echo "✅ InfluxDB already installed, skipping..."
fi

# ── Node.js ───────────────────────────────────────────────────────────────────

if ! command -v node &> /dev/null; then
    echo "📦 Installing Node.js..."
    curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
    sudo apt install -y nodejs
else
    echo "✅ Node.js already installed, skipping..."
fi

# ── Python venv ───────────────────────────────────────────────────────────────

if [ ! -d "$SCRIPT_DIR/sensors/venv" ]; then
    echo "🐍 Setting up Python environment..."
    cd "$SCRIPT_DIR/sensors"
    python3 -m venv venv
    venv/bin/pip install --upgrade pip
    venv/bin/pip install -r requirements.txt
else
    echo "✅ Python environment already set up, skipping..."
fi

# ── Systemd service ───────────────────────────────────────────────────────────

if ! systemctl is-enabled --quiet weather-sensors 2>/dev/null; then
    echo "⚙️  Installing systemd service..."
    sudo tee /etc/systemd/system/weather-sensors.service > /dev/null <<EOF
[Unit]
Description=Weather Station Sensors
After=network.target

[Service]
WorkingDirectory=$SCRIPT_DIR/sensors
ExecStart=$SCRIPT_DIR/sensors/venv/bin/python main.py
Restart=always
RestartSec=5
User=$USER_NAME

[Install]
WantedBy=multi-user.target
EOF
    sudo systemctl daemon-reload
    sudo systemctl enable --now weather-sensors
else
    echo "✅ Systemd service already installed, skipping..."
fi

echo "✅ All done!"
echo "   InfluxDB UI: http://localhost:8086"
echo "   Sensor logs: journalctl -fu weather-sensors"

