#!/bin/bash
# Installs (or repairs) the Cosmos Cloud desktop entry for the current user,
# pointing at wherever this folder currently lives.

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APPLICATIONS_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
ENTRY="$APPLICATIONS_DIR/cosmos-cloud.desktop"

# Escape a path for use inside a quoted Exec= argument, per the Desktop Entry
# Specification: \ " $ ` must be escaped with a backslash - which itself has to be
# doubled because \ is also an escape character in desktop-file values.
desktop_exec_quote() {
    printf '%s' "$1" | sed -e 's/\\/\\\\\\\\/g' -e 's/"/\\\\"/g' -e 's/\$/\\\\$/g' -e 's/`/\\\\`/g'
}

# Icon= is a plain string (not an exec line), so it is never quoted; only the
# desktop-file backslash escape applies.
desktop_value() {
    printf '%s' "$1" | sed -e 's/\\/\\\\/g'
}

mkdir -p "$APPLICATIONS_DIR"

cat > "$ENTRY" << ENTRY_EOF
[Desktop Entry]
Version=1.0
Type=Application
Name=Cosmos Cloud
Comment=Cosmos Cloud
Exec="$(desktop_exec_quote "$SCRIPT_DIR/cosmos-cloud.sh")"
Icon=$(desktop_value "$SCRIPT_DIR/data/flutter_assets/assets/icon.png")
Terminal=false
StartupWMClass=cosmos_cloud
Categories=Network;Security;
ENTRY_EOF

chmod +x "$ENTRY" 2>/dev/null || true
echo "Desktop entry installed at: $ENTRY"

if command -v update-desktop-database >/dev/null 2>&1; then
    update-desktop-database "$APPLICATIONS_DIR" >/dev/null 2>&1 || true
fi
