#!/usr/bin/env sh
# ==============================================================================
# Darkstars Linux Mobile Package Repository Setup
# Supports: Alpine Linux, postmarketOS, Nura
# ==============================================================================
set -eu

REPO_URL="https://apk.darkstars.me"
KEY_URL="${REPO_URL}/darkstars.rsa.pub"
KEY_DEST="/etc/apk/keys/darkstars.rsa.pub"
REPO_ENTRY="${REPO_URL}/packages"
REPO_FILE="/etc/apk/repositories"

if [ "$(id -u)" -ne 0 ]; then
    echo "ERROR: Please run this script as root (or with sudo):" >&2
    echo "  curl -fsSL https://apk.darkstars.me/setup.sh | sudo sh" >&2
    exit 1
fi

echo "==> [1/3] Downloading Darkstars repository signing key..."
mkdir -p /etc/apk/keys
if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$KEY_URL" -o "$KEY_DEST"
elif command -v wget >/dev/null 2>&1; then
    wget -qO "$KEY_DEST" "$KEY_URL"
else
    echo "ERROR: Neither curl nor wget found. Please install one first." >&2
    exit 1
fi
chmod 644 "$KEY_DEST"
echo "    Trusted key installed to $KEY_DEST"

echo "==> [2/3] Adding repository to $REPO_FILE..."
touch "$REPO_FILE"
if grep -Fxq "$REPO_ENTRY" "$REPO_FILE"; then
    echo "    Repository already present in $REPO_FILE"
else
    echo "$REPO_ENTRY" >> "$REPO_FILE"
    echo "    Added: $REPO_ENTRY"
fi

echo "==> [3/3] Updating APK package index..."
apk update

echo ""
echo "=============================================================================="
echo "  Success! Darkstars Mobile Repository is now configured."
echo "  You can now install applications using:"
echo "    sudo apk add me.darkstars.phlare"
echo "    sudo apk add me.darkstars.phoshcord"
echo "=============================================================================="
