#!/bin/bash
set -euo pipefail

APP_NAME="Cord"
DIR="build"
BUNDLE="${DIR}/${APP_NAME}.app"
BIN_NAME="cord-gui"

echo "building ${BIN_NAME}..."
cargo build --release -p cord-gui

echo "creating ${BUNDLE}..."
rm -rf "${DIR}"
mkdir -p "${DIR}"
mkdir -p "${BUNDLE}/Contents/MacOS"
mkdir -p "${BUNDLE}/Contents/Resources"

cp "target/release/${BIN_NAME}" "${BUNDLE}/Contents/MacOS/${BIN_NAME}"
cp "crates/cord-gui/Info.plist" "${BUNDLE}/Contents/Info.plist"

# Generate icon from SVG
ICON_SVG="static/vectors/cord.svg"
if [ -f "${ICON_SVG}" ] && command -v rsvg-convert &>/dev/null; then
    ICONSET="build/icon.iconset"
    rm -rf "${ICONSET}"
    mkdir -p "${ICONSET}"

    # iconutil requires exactly these sizes:
    #   icon_NxN.png      (1x)
    #   icon_NxN@2x.png   (retina — rendered at 2N)
    for sz in 16 32 128 256 512; do
        rsvg-convert -w ${sz} -h ${sz} "${ICON_SVG}" -o "${ICONSET}/icon_${sz}x${sz}.png"
        dbl=$((sz * 2))
        rsvg-convert -w ${dbl} -h ${dbl} "${ICON_SVG}" -o "${ICONSET}/icon_${sz}x${sz}@2x.png"
    done

    iconutil -c icns "${ICONSET}" -o "${BUNDLE}/Contents/Resources/AppIcon.icns"
    rm -rf "${ICONSET}"
    echo "icon generated"
else
    echo "no icon svg or rsvg-convert not found, skipping icon"
fi

echo "done: ${BUNDLE}"
echo "to register file types, run: open ${BUNDLE}"
