#!/bin/bash

# PScreen CLI Smart Installer v2.0.2
# Automatically installs or updates PScreen CLI

set -e

PACKAGE_URL="http://77.73.238.240:8081/pscreen-cli_2.0.2_all.deb"
PACKAGE_NAME="pscreen-cli_2.0.2_all.deb"
TEMP_DIR="/tmp/pscreen-install"

echo "🚀 PScreen CLI Smart Installer v2.0.2"
echo "=========================================="

# Create temp directory
mkdir -p "$TEMP_DIR"
cd "$TEMP_DIR"

# Check if pscreen is already installed
if command -v pscreen >/dev/null 2>&1; then
    CURRENT_VERSION=$(pscreen --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' || echo "unknown")
    echo "ℹ️  Current PScreen version: $CURRENT_VERSION"
    echo "🔄 Updating to version 2.0.2..."
else
    echo "📦 Installing PScreen CLI v2.0.2..."
fi

# Download package
echo "⬇️  Downloading package..."
if command -v wget >/dev/null 2>&1; then
    wget -q "$PACKAGE_URL" -O "$PACKAGE_NAME"
elif command -v curl >/dev/null 2>&1; then
    curl -s -L "$PACKAGE_URL" -o "$PACKAGE_NAME"
else
    echo "❌ Error: Neither wget nor curl is available"
    exit 1
fi

# Install package
echo "📦 Installing package..."
if dpkg -i "$PACKAGE_NAME" 2>/dev/null; then
    echo "✅ Package installed successfully"
else
    echo "🔧 Fixing dependencies..."
    apt-get update >/dev/null 2>&1
    apt-get install -f -y >/dev/null 2>&1
    echo "✅ Dependencies fixed"
fi

# Verify installation
if command -v pscreen >/dev/null 2>&1; then
    NEW_VERSION=$(pscreen --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' || echo "2.0.2")
    echo "✅ PScreen CLI v$NEW_VERSION installed successfully!"
    echo ""
    echo "🎯 Quick start:"
    echo "   pscreen screenshot https://example.com"
    echo "   pscreen serve"
    echo ""
    echo "📖 Get help: pscreen --help"
else
    echo "❌ Installation verification failed"
    exit 1
fi

# Cleanup
cd /
rm -rf "$TEMP_DIR"

echo "🎉 Installation complete!"
