#!/bin/bash
# vixy-vision Server Setup Script
# Run this on a Raspberry Pi or similar edge device
#
# Usage: ./setup.sh
#
# Reads SERVICE_NAME and PORT from .env file for multi-instance support

set -e

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

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
echo_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
echo_error() { echo -e "${RED}[ERROR]${NC} $1"; }

echo "=========================================="
echo "  vixy-vision Server Setup"
echo "  Eyes for the fox 🦊"
echo "=========================================="
echo ""

# Check if running on Linux
if [[ "$(uname)" != "Linux" ]]; then
    echo_error "This script is designed for Linux (Raspberry Pi)"
    exit 1
fi
# Check for .env file
if [ ! -f "${SCRIPT_DIR}/.env" ]; then
    echo_error "No .env file found!"
    echo_info "Copy env.example to .env and configure it first:"
    echo "  cp env.example .env"
    echo "  nano .env"
    exit 1
fi

# Load configuration from .env
source "${SCRIPT_DIR}/.env"

# Set defaults if not in .env
SERVICE_NAME="${SERVICE_NAME:-vixy-vision}"
PORT="${PORT:-8443}"
CAMERA_ID="${CAMERA_ID:-camera}"

echo_info "Configuration:"
echo "  SERVICE_NAME: ${SERVICE_NAME}"
echo "  PORT: ${PORT}"
echo "  CAMERA_ID: ${CAMERA_ID}"
echo ""

# Install directory based on service name
INSTALL_DIR="${HOME}/${SERVICE_NAME}"

# Install system dependencies
echo_info "Installing system dependencies..."
sudo apt-get update
sudo apt-get install -y python3-pip python3-venv libopencv-dev python3-opencv

# Create install directory
echo_info "Creating install directory: ${INSTALL_DIR}"
mkdir -p "${INSTALL_DIR}"
mkdir -p "${INSTALL_DIR}/ssl"

# Copy files
cp "${SCRIPT_DIR}/main.py" "${INSTALL_DIR}/"
cp "${SCRIPT_DIR}/motion.py" "${INSTALL_DIR}/"
cp "${SCRIPT_DIR}/detector.py" "${INSTALL_DIR}/"
cp "${SCRIPT_DIR}/requirements.txt" "${INSTALL_DIR}/"
cp "${SCRIPT_DIR}/generate_cert.sh" "${INSTALL_DIR}/"
cp "${SCRIPT_DIR}/.env" "${INSTALL_DIR}/"

# Copy model files
mkdir -p "${INSTALL_DIR}/models"
cp "${SCRIPT_DIR}/models/"* "${INSTALL_DIR}/models/"

# Create virtual environment
echo_info "Creating Python virtual environment..."
cd "${INSTALL_DIR}"
python3 -m venv venv
source venv/bin/activate

# Install Python dependencies
echo_info "Installing Python dependencies..."
pip install --upgrade pip
pip install -r requirements.txt

# Install TFLite runtime for object detection
echo_info "Installing TFLite runtime for object detection..."
pip install ai-edge-litert 2>/dev/null || \
pip install tflite-runtime 2>/dev/null || \
echo_warn "No TFLite runtime available for this platform (object detection will be disabled)"

# Generate SSL certificates if not present
if [ ! -f ssl/cert.pem ]; then
    echo_info "Generating SSL certificates..."
    chmod +x generate_cert.sh
    ./generate_cert.sh
else
    echo_info "SSL certificates already exist"
fi

# Create systemd service
echo_info "Creating systemd service: ${SERVICE_NAME}"
sudo tee /etc/systemd/system/${SERVICE_NAME}.service > /dev/null << EOF
[Unit]
Description=vixy-vision Camera Server (${CAMERA_ID})
After=network.target

[Service]
Type=simple
User=${USER}
WorkingDirectory=${INSTALL_DIR}
EnvironmentFile=${INSTALL_DIR}/.env
Environment="PATH=${INSTALL_DIR}/venv/bin"
ExecStart=${INSTALL_DIR}/venv/bin/uvicorn main:app --host 0.0.0.0 --port ${PORT} --ssl-keyfile ssl/key.pem --ssl-certfile ssl/cert.pem
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd and enable service
sudo systemctl daemon-reload
sudo systemctl enable ${SERVICE_NAME}

echo ""
echo "=========================================="
echo "  Setup Complete! 🦊"
echo "=========================================="
echo ""
echo "Service: ${SERVICE_NAME}"
echo "Port: ${PORT}"
echo "Camera ID: ${CAMERA_ID}"
echo ""
echo "Commands:"
echo "  Start:   sudo systemctl start ${SERVICE_NAME}"
echo "  Stop:    sudo systemctl stop ${SERVICE_NAME}"
echo "  Status:  sudo systemctl status ${SERVICE_NAME}"
echo "  Logs:    sudo journalctl -u ${SERVICE_NAME} -f"
echo ""
echo "Server will be available at:"
echo "  https://$(hostname).local:${PORT}/"
echo ""
echo "API Key from .env:"
grep "^API_KEY=" "${INSTALL_DIR}/.env" | cut -d'=' -f2
echo ""
echo_info "Start the server with: sudo systemctl start ${SERVICE_NAME}"
