#!/bin/bash

set -e

# Check if an AppImage path is provided
if [ -z "$1" ]; then
    echo "Usage: $0 /path/to/AppImage"
    exit 1
fi

# Absolute path to the AppImage
APPIMAGE_PATH="$(realpath "$1")"
# Application destination dir
APPDIR="$HOME/.local/share/applications"
# A place to store application icons
ICONDIR="$HOME/.local/share/icons"

# Make a tempdir and cd into it
EXTRACT_DIR=$(mktemp -d)
cleanup() {
	[ -z "$EXTRACT_DIR" ] && exit 2
	rm -rf "$EXTRACT_DIR"
}
trap cleanup EXIT
pushd "$EXTRACT_DIR"

# Extract AppImage
"$APPIMAGE_PATH" --appimage-extract > /dev/null 2>&1
# Find the extracted desktop file and icon
DESKTOP_FILE=$(find "$EXTRACT_DIR/squashfs-root" -name "*.desktop" | head -n 1)
# GPT spat this out and I'm really not sure if it's correct. I don't think
# fd spec limits us to these two file formats
ICON_FILE=$(find "$EXTRACT_DIR/squashfs-root" -name "*.png" -o -name "*.svg" | head -n 1)

if [ -z "$DESKTOP_FILE" ]; then
    echo "Error: No .desktop file found in AppImage."
    exit 1
fi

# Jump out of the tempdir. We now have absolute paths to the things we want
popd

APP_NAME=$(grep -m1 '^Name=' "$DESKTOP_FILE" | cut -d= -f2)
DESKTOP_TARGET="$APPDIR/$APP_NAME.desktop"
ICON_TARGET="$ICONDIR/$APP_NAME.${ICON_FILE##*.}"
# Copy the icon over
mkdir -p "$ICONDIR"
cp "$ICON_FILE" "$ICON_TARGET"
# Update paths in the .desktop file and copy it over
sed -e "s|^Exec=.*|Exec=$APPIMAGE_PATH|" \
    -e "s|^Icon=.*|Icon=$ICON_TARGET|" \
    "$DESKTOP_FILE" > "$DESKTOP_TARGET"
# Ensure the desktop file is executable
chmod +x "$DESKTOP_TARGET"

# Refresh application menu
update-desktop-database "$APPDIR"

echo "Desktop entry created: $DESKTOP_TARGET"
echo "Icon saved at: $ICON_TARGET"
echo "You can now launch '$APP_NAME' from your application menu."