#!/bin/bash
# DupFinder CLI wrapper
CONF_FILE="/etc/dupfinder.conf"
COMPOSE_DIR="/opt/dupfinder"
COMPOSE_YML="$COMPOSE_DIR/docker-compose.yml"
OVERRIDE_YML="$COMPOSE_DIR/docker-compose.override.yml"

[[ -f "$CONF_FILE" ]] && source "$CONF_FILE"
: "${APP_PORT:=8765}"

_compose() {
    docker compose -f "$COMPOSE_YML" -f "$OVERRIDE_YML" "$@"
}

_require_conf() {
    if [[ ! -f "$CONF_FILE" ]]; then
        echo "DupFinder is not configured. Run: sudo dupfinder setup"
        exit 1
    fi
}

case "${1:-help}" in
    setup)
        exec bash /opt/dupfinder/dupfinder-setup.sh
        ;;
    start)
        _require_conf
        sudo systemctl start dupfinder.service
        echo "DupFinder started — http://localhost:$APP_PORT"
        ;;
    stop)
        sudo systemctl stop dupfinder.service
        echo "DupFinder stopped."
        ;;
    restart)
        _require_conf
        sudo systemctl restart dupfinder.service
        echo "DupFinder restarted — http://localhost:$APP_PORT"
        ;;
    status)
        systemctl status dupfinder.service --no-pager
        ;;
    logs)
        _compose logs -f --tail=100
        ;;
    open)
        _require_conf
        # Wait for service to be ready then open browser
        for i in $(seq 1 15); do
            curl -sf "http://localhost:$APP_PORT/" -o /dev/null && break
            sleep 1
        done
        xdg-open "http://localhost:$APP_PORT" 2>/dev/null || \
        echo "Open in browser: http://localhost:$APP_PORT"
        ;;
    update)
        _require_conf
        echo "Pulling latest image..."
        docker pull tocmo0nlord/dupfinder:latest
        sudo systemctl restart dupfinder.service
        echo "Updated and restarted."
        ;;
    uninstall)
        echo "To fully remove DupFinder:  sudo apt remove dupfinder"
        echo "To also remove data:        sudo apt purge dupfinder"
        ;;
    help|--help|-h|*)
        echo "Usage: dupfinder <command>"
        echo ""
        echo "Commands:"
        echo "  setup      Configure photos path, data path, pull image"
        echo "  start      Start the service"
        echo "  stop       Stop the service"
        echo "  restart    Restart the service"
        echo "  status     Show systemd service status"
        echo "  logs       Tail container logs"
        echo "  open       Open in browser"
        echo "  update     Pull latest image and restart"
        echo "  uninstall  Show removal instructions"
        ;;
esac
