#!/usr/bin/env bash
set -euo pipefail

WORKDIR=${WORKDIR:-/var/www/html}
SRC_DIR="${WORKDIR}/clients/photobooth-uploader/PhotoboothUploader"
OUT_DIR="${WORKDIR}/public/downloads"
WIN_FILE="${OUT_DIR}/PhotoboothUploader-win-x64.exe"
MAC_FILE="${OUT_DIR}/PhotoboothUploader-macos-x64"
LINUX_FILE="${OUT_DIR}/PhotoboothUploader-linux-x64"
STAMP_FILE="${OUT_DIR}/photobooth-uploader.hash"

if [[ ! -d "$SRC_DIR" ]]; then
    echo "[photobooth-uploader] Source directory not found: ${SRC_DIR}"
    exit 0
fi

mkdir -p "$OUT_DIR"

compute_hash() {
    find "$SRC_DIR" -type f \
        -not -path "*/bin/*" \
        -not -path "*/obj/*" \
        -print \
        | LC_ALL=C sort \
        | xargs sha256sum \
        | sha256sum \
        | awk '{print $1}'
}

HASH=$(compute_hash)

if [[ -f "$WIN_FILE" && -f "$MAC_FILE" && -f "$LINUX_FILE" && -f "$STAMP_FILE" ]]; then
    CURRENT_HASH=$(cat "$STAMP_FILE" || true)
    if [[ "$CURRENT_HASH" == "$HASH" ]]; then
        echo "[photobooth-uploader] Up to date, skipping publish."
        exit 0
    fi
fi

publish_target() {
    local rid="$1"
    local output_file="$2"
    local temp_dir
    temp_dir=$(mktemp -d)

    dotnet publish "${SRC_DIR}/PhotoboothUploader.csproj" \
        -c Release \
        -r "$rid" \
        --self-contained true \
        /p:PublishSingleFile=true \
        /p:IncludeNativeLibrariesForSelfExtract=true \
        -o "$temp_dir"

    if [[ "$rid" == "win-x64" ]]; then
        mv -f "$temp_dir/PhotoboothUploader.exe" "$output_file"
    else
        mv -f "$temp_dir/PhotoboothUploader" "$output_file"
    fi

    rm -rf "$temp_dir"
}

echo "[photobooth-uploader] Publishing uploader binaries..."
publish_target "win-x64" "$WIN_FILE"
publish_target "osx-x64" "$MAC_FILE"
publish_target "linux-x64" "$LINUX_FILE"

echo "$HASH" > "$STAMP_FILE"
echo "[photobooth-uploader] Published to ${OUT_DIR}"
