#!/bin/sh

die() {
    >&2 echo "error: $*"
    exit 1
}

set -e

PHP="$(which php)"
SCRIPT_DIR=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)
APP_DIR="$(realpath "$SCRIPT_DIR/../")"
OUTPUT_ROOT_DIR=
PREV_COMMIT=

usage() {
    cat <<EOF
usage: $(basename "$0") [OPTIONS]

Options:
    -o  output directory
    -p  previous commit hash
    -h  show this help
EOF
    exit 1
}

while [ $# -gt 0 ]; do
    case $1 in
        -o) OUTPUT_ROOT_DIR="$2"; shift ;;
        -p) PREV_COMMIT="$2"; shift ;;
        -h) usage ;;
        *) die "unexpected argument: $1" ;;
    esac
    shift
done
[ -z "$OUTPUT_ROOT_DIR" ] && die "you must specify output directory"

# Get current commit hash
CURR_COMMIT=$(git rev-parse HEAD)

# Detect which projects have changed
CHANGED_PROJECTS=$("$SCRIPT_DIR"/util/detect_changes.sh -a "$APP_DIR" -p "$PREV_COMMIT" -c "$CURR_COMMIT")

# If no projects have changed, just update the commit hash in config-runtime.php
if [ -z "$CHANGED_PROJECTS" ]; then
    echo "No static files have changed, only updating commit hash in config-runtime.php"
    $PHP "$SCRIPT_DIR"/util/gen_runtime_config_incremental.php \
        --app-root "$OUTPUT_ROOT_DIR" \
        --commit-hash "$CURR_COMMIT" \
        --config-file "$OUTPUT_ROOT_DIR/config-runtime.php" \
        > "$OUTPUT_ROOT_DIR/config-runtime.php.new" || die "gen_runtime_config_incremental failed"
    mv "$OUTPUT_ROOT_DIR/config-runtime.php.new" "$OUTPUT_ROOT_DIR/config-runtime.php"
    exit 0
fi

echo "Rebuilding static for projects: $CHANGED_PROJECTS"

# Create output directories if they don't exist
for project in $CHANGED_PROJECTS; do
    mkdir -p "$OUTPUT_ROOT_DIR/public/$project/dist-css"
    mkdir -p "$OUTPUT_ROOT_DIR/public/$project/dist-js"
done

# Build static for changed projects
for project in $CHANGED_PROJECTS; do
    echo "Building CSS for $project..."
    "$SCRIPT_DIR"/util/build_css.sh -i "$APP_DIR/public/$project/scss" -o "$OUTPUT_ROOT_DIR/public/$project/dist-css" || die "build_css failed for $project"

    echo "Building JS for $project..."
    "$SCRIPT_DIR"/util/build_js.sh -i "$APP_DIR/public/common/js" -o "$OUTPUT_ROOT_DIR/public/$project/dist-js" || die "build_js failed for $project"
done

# Generate runtime config with integrity hashes
echo "Generating runtime config..."
$PHP "$SCRIPT_DIR"/util/gen_runtime_config_incremental.php \
    --app-root "$OUTPUT_ROOT_DIR" \
    --commit-hash "$CURR_COMMIT" \
    --changed-projects "$CHANGED_PROJECTS" \
    --config-file "$OUTPUT_ROOT_DIR/config-runtime.php" \
    > "$OUTPUT_ROOT_DIR/config-runtime.php.new" || die "gen_runtime_config_incremental failed"
mv "$OUTPUT_ROOT_DIR/config-runtime.php.new" "$OUTPUT_ROOT_DIR/config-runtime.php"

echo "Static build completed successfully"
