#!/usr/bin/env bash

UUID="breezydesktop@xronlinux.com"

# fail on error
set -e

# https://stackoverflow.com/a/246128
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)

SRC_DIR="$SCRIPT_DIR/../src"
TMP_DIR=$(mktemp -d -t breezy-gnome-XXXXXXXXXX)
DEST_DIR="$TMP_DIR/$UUID"
OUT_DIR="$SCRIPT_DIR/../out"
rm -rf "$OUT_DIR"

cd "$SCRIPT_DIR" || exit 1

check_command() {
    if ! command -v "$1" &>/dev/null; then
        echo "Please install \"$1\" and make sure it's available in your \$PATH"
        exit 1
    fi
}

compile_schemas() {
    check_command "glib-compile-schemas"
    mkdir -p "$DEST_DIR/schemas/"

    # the pack command also compiles the schemas but only into the zip file
    glib-compile-schemas --targetdir="$DEST_DIR/schemas" "$SRC_DIR/schemas/"
}

copy_static_files() {
    # Copy non generated files to destdir
    cp $SRC_DIR/*.js $DEST_DIR/
    cp $SRC_DIR/*.frag $DEST_DIR/
    mkdir -p "$DEST_DIR/schemas/"
    cp $SRC_DIR/schemas/*.xml $DEST_DIR/schemas/
    mkdir -p $DEST_DIR/dbus-interfaces/
    cp $SRC_DIR/dbus-interfaces/*.xml $DEST_DIR/dbus-interfaces/
    mkdir -p $DEST_DIR/textures/
    cp -rL $SRC_DIR/textures/* $DEST_DIR/textures/
    cp $SRC_DIR/metadata.json $DEST_DIR/
}

pack() {
    check_command "gnome-extensions"

    # pack everything into a sharable zip file
    extra_source=()
    for file in "$DEST_DIR"/*; do
        extra_source+=("--extra-source=$file")
    done

    mkdir -p "$OUT_DIR"
    gnome-extensions pack --force "${extra_source[@]}" "$DEST_DIR" -o "$OUT_DIR"
}

if [ $# -eq 0 ]; then
    # No arguments, do everything
    compile_schemas
    copy_static_files
    pack
elif [ "$1" == "build_local" ]; then
    compile_schemas
    copy_static_files
elif [ "$1" == "pack" ]; then
    pack
elif [ "$1" == "copy_static" ]; then
    copy_static_files
fi

rm -rf "$TMP_DIR"