#!/bin/bash
set -e

# Check for root privileges
if [ "$EUID" -ne 0 ]; then 
    echo "ERROR: This script must be run as root"
    echo "Please run: sudo $0"
    exit 1
fi

echo "stillControl bootc Installation Script"
echo "======================================"

# Enable usr-overlay for bootc systems
echo "Enabling usr-overlay for bootc..."
bootc usr-overlay || true

# Get Python site-packages directory
PYTHON_SITELIB=$(python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))")
echo "Python site-packages directory: $PYTHON_SITELIB"

# Build gresources
echo "Building gresources..."
cd "$(dirname "$0")"
rm -f data/io.stillhq.control.gresource
glib-compile-resources --sourcedir data --generate data/io.stillhq.control.gresource.xml

# Create installation directories
echo "Creating installation directories..."
mkdir -p "$PYTHON_SITELIB/stillControl/data"
mkdir -p "$PYTHON_SITELIB/stillControl/layouts"
mkdir -p "$PYTHON_SITELIB/stillControl/UIs"
mkdir -p /usr/bin
mkdir -p /usr/share/icons/hicolor/scalable/apps
mkdir -p /usr/share/applications/
mkdir -p /usr/share/glib-2.0/schemas

# Install files
echo "Installing files..."

# Copy all project files to Python site-packages
echo "  - Copying project files to $PYTHON_SITELIB/stillControl..."
cp -r . "$PYTHON_SITELIB/stillControl/"

# Install binary
echo "  - Installing binary to /usr/bin/still-control..."
install -m 0755 __main__.py /usr/bin/still-control

# Install desktop file
echo "  - Installing desktop file..."
install -m 0755 data/stillControl.desktop /usr/share/applications/stillControl.desktop

# Install icon
echo "  - Installing icon..."
install -m 0644 data/stillControl.svg /usr/share/icons/hicolor/scalable/apps/stillControl.svg

# Install GSettings schema
echo "  - Installing GSettings schema..."
install -m 0644 data/io.stillhq.control.gschema.xml /usr/share/glib-2.0/schemas/

# Compile GSettings schemas
echo "Compiling GSettings schemas..."
glib-compile-schemas /usr/share/glib-2.0/schemas/

# Update icon cache
echo "Updating icon cache..."
gtk-update-icon-cache -f -t /usr/share/icons/hicolor/ 2>/dev/null || true

echo ""
echo "======================================"
echo "Installation complete!"
echo "You can now run: still-control"
echo "Or launch from applications menu: stillControl"
echo "======================================"
