#!/usr/bin/env bash
set -Eeuo pipefail
#set -x

function json-minify { ## Minify JSON data
    for JSON in assets/project.ldtk assets/*.json; do
        if [[ -e "$JSON".orig ]]; then
            echo "Error: $JSON.orig already exists"
            exit 1
        fi
        mv "$JSON"{,.orig} && jq '.' --compact-output "$JSON".orig > "$JSON"
    done
}

function json-restore { ## Restore original JSON data
    for JSON in assets/project.ldtk assets/*.json; do
        if [[ -e "$JSON".orig ]]; then
            mv "$JSON"{.orig,}
        fi
    done
}

function linux-glibc { ## Check glibc versions used in Linux release
    TARGET=x86_64-unknown-linux-gnu
    LINUX_RELEASE_BIN="target/$TARGET/release/corics-quest"
    [[ -e "$LINUX_RELEASE_BIN" ]] || {
        echo "Error: run cargo b --release --target $TARGET first"
        exit 1
    }
    echo glibc versions used in Linux release:
    objdump -T "$LINUX_RELEASE_BIN" | grep GLIBC | sed 's/.*GLIBC_\([.0-9]*\).*/\1/g' | sort -u
}

function linux-play-sh {
    echo '#!/bin/sh'
    echo 'cd "$(dirname "$(realpath "$0")")" && exec ./corics-quest'
}

function linux-zip { ## Build and zip Linux release
    TARGET=x86_64-unknown-linux-gnu
    cargo build --release --target "$TARGET"

    # Prepare zip directory.
    VERSION=$(cargo read-manifest | jq --raw-output '.version')
    BASE_NAME="corics_quest-$VERSION-$TARGET"
    DEST_DIR="target/zip/$BASE_NAME"
    mkdir --parents "$DEST_DIR" && touch "$DEST_DIR"
    cp "target/$TARGET/release/corics-quest" "$DEST_DIR/"
    awk -f prepare_txt.awk README.md > "$DEST_DIR/README.txt"
    awk -f prepare_txt.awk LICENSE.txt > "$DEST_DIR/LICENSE.txt"
    cp assets/icon-64.png "$DEST_DIR/corics-quest.png"
    linux-play-sh > "$DEST_DIR/play.sh" && chmod +x "$DEST_DIR/play.sh"

    # Make the zip with the directory.
    cd target/zip/
    zip --filesync --recurse-paths "$BASE_NAME.zip" "$BASE_NAME"
    echo "Linux zip: file://$(realpath "$BASE_NAME.zip")"
}

function windows-zip { ## Build and zip Windows release
    TARGET=x86_64-pc-windows-gnu
    cargo build --release --target "$TARGET"

    # Prepare zip directory.
    VERSION=$(cargo read-manifest | jq --raw-output '.version')
    BASE_NAME="corics_quest-$VERSION-$TARGET"
    DEST_DIR="target/zip/$BASE_NAME"
    mkdir --parents "$DEST_DIR" && touch "$DEST_DIR"
    cp "target/$TARGET/release/corics-quest.exe" "$DEST_DIR/"
    awk -f prepare_txt.awk README.md | unix2dos > "$DEST_DIR/README.txt"
    awk -f prepare_txt.awk LICENSE.txt | unix2dos > "$DEST_DIR/LICENSE.txt"
    cp assets/icon-64.png "$DEST_DIR/corics-quest.png"

    # Make the zip with the directory.
    cd target/zip/
    zip --filesync --recurse-paths "$BASE_NAME.zip" "$BASE_NAME"
    echo "Windows zip: file://$(realpath "$BASE_NAME.zip")"
}

function wasm-dir-test {
    if [[ ! -v WASM_DIR || -z $WASM_DIR ]]; then
        echo Error: set WASM_DIR environment variable first
        exit 1
    fi
    if [[ ! -d $WASM_DIR ]]; then
        echo Error: create WASM_DIR first "(${WASM_DIR})"
        exit 1
    fi
    if [[ ! -e "${WASM_DIR%/}"/gl.js ]]; then
        echo Error: WASM_DIR must contain gl.js: "(${WASM_DIR})"
        exit 1
    fi
    echo "WASM_DIR=${WASM_DIR}"
}

function wasm-site { ## Build and copy Wasm to website directory
    wasm-dir-test
    cargo build --release --target wasm32-unknown-unknown
    cp --update --preserve target/wasm32-unknown-unknown/release/corics-quest.wasm "$WASM_DIR"
}

function wasm-serve { ## Run HTTP server in Wasm/website directory
    wasm-dir-test
    cd "$WASM_DIR" && python3 -m http.server
}

function wasm-zip { ## Zip Wasm build and website directory
    # Ensure Wasm build in the website directory is up-to-date and WASM_DIR is set.
    wasm-site

    REAL_WASM_DIR=$(realpath "$WASM_DIR")

    mkdir --parents target/zip
    cd target/zip/

    VERSION=$(cargo read-manifest | jq --raw-output '.version')
    WASM_ZIP="corics_quest-$VERSION-wasm.zip"

    # Remove '/' suffix from REAL_WASM_DIR to avoid doubling up forward slashes.
    zip --filesync --junk-paths "$WASM_ZIP" \
        "${REAL_WASM_DIR%/}"/{corics-quest.wasm,index.html,*.js}

    echo "Wasm zip: file://$(realpath "$WASM_ZIP")"
}

function help { ## Show this help text
    echo "Usage: $0 [task-name]"
    echo Tasks:
    awk 'BEGIN { n = 0 } \
        /^function [^#]+##/ { \
            n++; \
            split($0, t, /## /); \
            printf "%6d  %-16s %s\n", n, $2, t[2]; \
        }' \
        "$0"
}

if [[ $# -gt 0 && ("$1" = "-h" || "$1" = "--help") ]]; then
    help
else
    "${@:-help}"
fi
