#!/bin/bash
# Smart Student Portal CLI Management Tool

SERVICE="classroom-attendance.service"
APP_DIR="/opt/smart-student-portal"
PYTHON="$APP_DIR/.venv/bin/python3"

case "$1" in
    start)
        echo "Starting Smart Student Portal..."
        systemctl start $SERVICE
        systemctl status $SERVICE --no-pager
        ;;
    stop)
        echo "Stopping Smart Student Portal..."
        systemctl stop $SERVICE
        ;;
    restart)
        echo "Restarting Smart Student Portal..."
        systemctl restart $SERVICE
        systemctl status $SERVICE --no-pager
        ;;
    status)
        systemctl status $SERVICE --no-pager
        ;;
    logs)
        journalctl -u $SERVICE -f -n 50
        ;;
    sync)
        echo "Triggering direct sync with Cloudflare D1 Cloud Portal..."
        if [ -f "$APP_DIR/direct_sync.py" ]; then
            cd "$APP_DIR" && "$PYTHON" direct_sync.py
        else
            curl -s -X POST http://127.0.0.1:8000/api/sync
            echo ""
        fi
        ;;
    open)
        xdg-open "http://127.0.0.1:8000" 2>/dev/null || sensible-browser "http://127.0.0.1:8000"
        ;;
    student|pwa)
        xdg-open "http://127.0.0.1:8000/student" 2>/dev/null || sensible-browser "http://127.0.0.1:8000/student"
        ;;
    update)
        echo "Checking for Smart Student Portal updates..."
        LATEST_INFO=$(curl -s "https://ssp-teachers.pages.dev/version.json" || true)
        if [ -z "$LATEST_INFO" ]; then
            echo "Unable to reach update server (offline or no internet)."
            exit 0
        fi
        LATEST_VER=$(echo "$LATEST_INFO" | grep -o '"latest_version": "[^"]*' | cut -d'"' -f4)
        if [ "$LATEST_VER" != "2.2.0" ] && [ -n "$LATEST_VER" ]; then
            echo "New version available: v$LATEST_VER (Current: v2.2.0)"
            echo "Downloading updated package..."
            curl -sSL "https://ssp-teachers.pages.dev/downloads/smart-student-portal_${LATEST_VER}_all.deb" -o /tmp/ssp_update.deb
            dpkg -i /tmp/ssp_update.deb
            rm -f /tmp/ssp_update.deb
            echo "Smart Student Portal updated to v$LATEST_VER successfully!"
        else
            echo "Smart Student Portal is already up to date (v2.2.0)."
        fi
        ;;
    *)
        echo "Smart Student Portal (v2.2.0) - Management CLI"
        echo "Usage: smart-student-portal {start|stop|restart|status|logs|sync|open|pwa|update}"
        exit 1
        ;;
esac
