#!/usr/bin/env bash

set -e

echo -e "\033[0;36mBuilding AppImage for OpenLoco...\033[0m"

# Ensure we are in root directory
cd "$(dirname "$0")/.."

# AppImage builds are only supported on Linux x86_64
if [[ "$(uname -s)" != "Linux" || "$(uname -m)" != "x86_64" ]]; then
    echo "AppImage builds are only supported on Linux x86_64, not $(uname -s) $(uname -m)" >&2
    exit 1
fi

appdir="$INPUT_PATH"

if [[ ! -d "$appdir" ]]; then
    echo "AppDir not found at ${appdir}. Build and install first:" >&2
    exit 1
fi

if [[ ! -d "$OUTPUT_PATH" ]]; then
    echo "Output path not found at ${OUTPUT_PATH}. Create it first:" >&2
    echo "  mkdir -p ${OUTPUT_PATH}" >&2
    exit 1
fi

linuxdeploy=/tmp/linuxdeploy-x86_64.AppImage
curl -fLo "$linuxdeploy" https://github.com/TheAssassin/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage
chmod +x "$linuxdeploy"
"$linuxdeploy" --appimage-extract-and-run --appdir "$appdir" --output appimage --desktop-file "$appdir/usr/share/applications/openloco.desktop"

# If APPIMAGE_FILE_NAME is set, use it as the filename, otherwise use the default
# Version tag, e.g. "v26.08-18" (mirrors cmake/OpenLocoVersion.cmake)
if [[ -z "$APPIMAGE_FILE_NAME" ]]; then
    APPIMAGE_FILE_NAME="OpenLoco-$(git describe HEAD --always | sed -E 's/-g[0-9a-f]+$//')-linux-x64.AppImage"
fi
mv OpenLoco-x86_64.AppImage "$OUTPUT_PATH/${APPIMAGE_FILE_NAME}"
rm "$linuxdeploy"

echo -e "\033[0;36mDone: $OUTPUT_PATH/${APPIMAGE_FILE_NAME}\033[0m"
