#!/usr/bin/env bash

set -euo pipefail

REPOSITORY_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PROJECT_DIR="$REPOSITORY_DIR/FchatiApp"
BUILD_DIR="$PROJECT_DIR/.build"
PRODUCT_NAME="FchatiApp"
INSTALL_PATH="/Applications/Fchati.app"
STAGING_DIR="$(mktemp -d "${TMPDIR:-/tmp}/fchati-install.XXXXXX")"
STAGING_APP="$STAGING_DIR/Fchati.app"
ICON_PATH="$PROJECT_DIR/Resources/Fchati.icns"

cleanup() {
    rm -rf "$STAGING_DIR"
}
trap cleanup EXIT

if [[ ! -f "$PROJECT_DIR/Package.swift" ]]; then
    echo "FchatiApp package not found: $PROJECT_DIR" >&2
    exit 1
fi

if [[ ! -f "$ICON_PATH" ]]; then
    echo "Application icon not found: $ICON_PATH" >&2
    exit 1
fi

if [[ -e "$INSTALL_PATH" && ! -d "$INSTALL_PATH" ]]; then
    echo "Expected an application bundle at $INSTALL_PATH, but found a non-directory." >&2
    exit 1
fi

echo "Removing the current Swift build artifacts..."
rm -rf "$BUILD_DIR"

echo "Running tests..."
swift test --package-path "$PROJECT_DIR"

echo "Building the release executable..."
swift build --configuration release --package-path "$PROJECT_DIR"

EXECUTABLE_PATH="$PROJECT_DIR/.build/release/$PRODUCT_NAME"
if [[ ! -x "$EXECUTABLE_PATH" ]]; then
    echo "Release executable not found: $EXECUTABLE_PATH" >&2
    exit 1
fi

echo "Creating the application bundle..."
mkdir -p "$STAGING_APP/Contents/MacOS" "$STAGING_APP/Contents/Resources"
cp "$PROJECT_DIR/Info.plist" "$STAGING_APP/Contents/Info.plist"
cp "$EXECUTABLE_PATH" "$STAGING_APP/Contents/MacOS/$PRODUCT_NAME"
cp "$ICON_PATH" "$STAGING_APP/Contents/Resources/Fchati.icns"
codesign --force --sign - --timestamp=none --entitlements "$PROJECT_DIR/FchatiApp.entitlements" "$STAGING_APP"

if [[ -d "$INSTALL_PATH" ]]; then
    echo "Removing the installed application..."
    rm -rf "$INSTALL_PATH"
fi

echo "Installing the application..."
mv "$STAGING_APP" "$INSTALL_PATH"

echo "Opening Fchati..."
open "$INSTALL_PATH"

echo "Fchati was installed and opened successfully."
