#!/bin/bash
set -e

# HVAC Know It All Content Scraper Installation Script

INSTALL_DIR="/opt/hvac-kia-content"
SERVICE_USER="ben"
CURRENT_DIR="$(pwd)"

echo "Installing HVAC Know It All Content Scraper..."

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root (use sudo)" 
   exit 1
fi

# Create installation directory
echo "Creating installation directory..."
mkdir -p "$INSTALL_DIR"

# Copy application files
echo "Copying application files..."
cp -r src/ "$INSTALL_DIR/"
cp -r requirements.txt "$INSTALL_DIR/"
cp -r .env "$INSTALL_DIR/"
cp -r pyproject.toml "$INSTALL_DIR/"

# Set ownership
echo "Setting ownership..."
chown -R "$SERVICE_USER:$SERVICE_USER" "$INSTALL_DIR"

# Create Python virtual environment
echo "Setting up Python environment..."
cd "$INSTALL_DIR"
sudo -u "$SERVICE_USER" python3 -m venv .venv
sudo -u "$SERVICE_USER" .venv/bin/pip install -r requirements.txt

# Create directories
echo "Creating data directories..."
sudo -u "$SERVICE_USER" mkdir -p "$INSTALL_DIR"/{logs,data,.state}
sudo -u "$SERVICE_USER" mkdir -p /mnt/nas/hvacknowitall

# Install systemd services
echo "Installing systemd services..."
cp "$CURRENT_DIR/systemd/hvac-scraper.service" /etc/systemd/system/
cp "$CURRENT_DIR/systemd/hvac-scraper-morning.timer" /etc/systemd/system/
cp "$CURRENT_DIR/systemd/hvac-scraper-afternoon.timer" /etc/systemd/system/

# Reload systemd and enable services
echo "Enabling systemd services..."
systemctl daemon-reload
systemctl enable hvac-scraper.service
systemctl enable hvac-scraper-morning.timer
systemctl enable hvac-scraper-afternoon.timer

# Start timers
echo "Starting timers..."
systemctl start hvac-scraper-morning.timer
systemctl start hvac-scraper-afternoon.timer

echo ""
echo "✅ Installation complete!"
echo ""
echo "Service status:"
systemctl status hvac-scraper-morning.timer --no-pager -l
systemctl status hvac-scraper-afternoon.timer --no-pager -l

echo ""
echo "Manual execution:"
echo "  sudo systemctl start hvac-scraper.service"
echo ""
echo "View logs:"
echo "  journalctl -u hvac-scraper.service -f"
echo ""
echo "Timer schedule:"
echo "  systemctl list-timers hvac-scraper-*"