#!/usr/bin/env bash
# Install this SaDB checkout system-wide for local stillCenter testing.

set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
REFRESH=true

usage() {
    cat <<EOF
Usage: sudo $0 [--no-refresh]

Installs the current SaDB source tree, CLI, and default stillOS configuration.
By default it then rebuilds /var/lib/sadb/sadb.db and restarts SAM if active.

  --no-refresh  Install files without downloading/rebuilding the database
  -h, --help    Show this help
EOF
}

for argument in "$@"; do
    case "$argument" in
        --no-refresh) REFRESH=false ;;
        -h|--help) usage; exit 0 ;;
        *) echo "Unknown argument: $argument" >&2; usage >&2; exit 2 ;;
    esac
done

if [[ $EUID -ne 0 ]]; then
    echo "Run this installer as root: sudo $0" >&2
    exit 1
fi

for command in python3 install; do
    command -v "$command" >/dev/null || {
        echo "Missing required command: $command" >&2
        exit 1
    }
done

python3 - <<'PY'
import gi
import yaml
gi.require_version("AppStream", "1.0")
from gi.repository import AppStream  # noqa: F401
PY

PYTHON_SITELIB="$(python3 -c 'import sysconfig; print(sysconfig.get_path("platlib"))')"
SADB_SITELIB="$PYTHON_SITELIB/sadb"

echo "Installing SaDB modules to $SADB_SITELIB"
install -d -m 0755 "$SADB_SITELIB/source" /usr/bin /etc
install -m 0644 "$SCRIPT_DIR"/src/*.py "$SADB_SITELIB/"
install -m 0644 "$SCRIPT_DIR"/src/source/*.py "$SADB_SITELIB/source/"
install -m 0755 "$SCRIPT_DIR/src/__main__.py" /usr/bin/sadb

if [[ ! -f /etc/sadb.conf ]]; then
    install -m 0644 "$SCRIPT_DIR/ex_config_files/sadb.conf" /etc/sadb.conf
    echo "Installed /etc/sadb.conf"
else
    echo "Preserving existing /etc/sadb.conf"
fi

if [[ "$REFRESH" == true ]]; then
    echo "Refreshing SaDB sources and application database"
    /usr/bin/sadb update-source
    /usr/bin/sadb update-db
    /usr/bin/sadb update-installed
fi

if systemctl is-active --quiet sam.service 2>/dev/null; then
    echo "Restarting SAM to load the updated SaDB modules"
    systemctl restart sam.service
fi

python3 - <<'PY'
import sadb
import sadb.appstream_metadata
print(f"Installed SaDB from {sadb.__file__}")
PY

echo "SaDB test installation complete. Restart stillCenter before testing."
