#!/bin/bash
set -e

INSTALL_DIR="/opt/PiScope"
VENV_DIR="$INSTALL_DIR/venv"
SERVICE_FILE="piscope.service"

echo "=== Orange Pi OLED Monitor Installer ==="

if [ "$EUID" -ne 0 ]; then
  echo "Please run as root (sudo ./install.sh)"
  exit 1
fi

echo "[1/6] Creating $INSTALL_DIR"
mkdir -p "$INSTALL_DIR"

echo "[2/6] Copying files"
cp PiScope.py requirements.txt "$INSTALL_DIR/"
cp "$SERVICE_FILE" "$INSTALL_DIR/"

echo "[3/6] Creating Python virtual environment"
python3 -m venv "$VENV_DIR"

echo "[4/6] Installing Python dependencies"
"$VENV_DIR/bin/pip" install --upgrade pip
"$VENV_DIR/bin/pip" install -r "$INSTALL_DIR/requirements.txt"

echo "[5/6] Installing systemd service"
cp "$INSTALL_DIR/$SERVICE_FILE" /etc/systemd/system/
systemctl daemon-reload
systemctl enable --now piscope.service

echo "[6/6] Installation complete!"
echo
echo "MANUAL STEPS REQUIRED:"
echo "1) Run: orange-pi-config"
echo "2) Enable I2C3"
echo "3) Reboot the system"
echo "4) Connect OLED to I2C3 pins (SDA/SCL + 3.3V + GND)"
echo
echo "Check logs with:"
echo "  journalctl -u piscope.service -f"
