#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

SVG="assets/cue.svg"
NAME="Cue"
BIN="cue"
VERSION="0.1.0"
IDENTIFIER="org.else-if.cue"

if [ ! -f "$SVG" ]; then
    echo "Error: $SVG not found"
    exit 1
fi

render_svg() {
    local svg="$1" size="$2" out="$3"
    if command -v rsvg-convert >/dev/null 2>&1; then
        rsvg-convert -w "$size" -h "$size" "$svg" -o "$out"
    elif command -v magick >/dev/null 2>&1; then
        # Compute DPI so SVG viewport rasterizes at target pixel size.
        # Default 72 DPI renders the 83.25-unit viewport at 83px;
        # scaling DPI proportionally renders at exact target dimensions.
        local dpi=$(( (size * 72 + 82) / 83 ))
        magick -background none -density "$dpi" "$svg" \
            -resize "${size}x${size}" "PNG32:$out"
    else
        echo "Error: need rsvg-convert (librsvg) or magick (ImageMagick 7)"
        exit 1
    fi
}

case "$(uname -s)" in
    Darwin)
        echo "==> Generating .icns"
        ICONSET=$(mktemp -d)/cue.iconset
        mkdir -p "$ICONSET"
        for size in 16 32 128 256 512; do
            render_svg "$SVG" "$size" "$ICONSET/icon_${size}x${size}.png"
            double=$((size * 2))
            render_svg "$SVG" "$double" "$ICONSET/icon_${size}x${size}@2x.png"
        done
        iconutil -c icns "$ICONSET" -o assets/cue.icns
        rm -rf "$(dirname "$ICONSET")"

        echo "==> cargo build --release"
        cargo build --release

        echo "==> Creating .app bundle"
        APP="target/release/$NAME.app"
        rm -rf "$APP"
        mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
        cp "target/release/$BIN" "$APP/Contents/MacOS/$NAME"
        cp assets/cue.icns "$APP/Contents/Resources/"

        cat > "$APP/Contents/Info.plist" << PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleName</key>
    <string>$NAME</string>
    <key>CFBundleDisplayName</key>
    <string>$NAME</string>
    <key>CFBundleIdentifier</key>
    <string>$IDENTIFIER</string>
    <key>CFBundleVersion</key>
    <string>$VERSION</string>
    <key>CFBundleShortVersionString</key>
    <string>$VERSION</string>
    <key>CFBundleExecutable</key>
    <string>$NAME</string>
    <key>CFBundleIconFile</key>
    <string>cue</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>NSHighResolutionCapable</key>
    <true/>
    <key>NSBluetoothAlwaysUsageDescription</key>
    <string>Cue uses Bluetooth to communicate with EIS4.</string>
    <key>NSBluetoothPeripheralUsageDescription</key>
    <string>Cue uses Bluetooth to communicate with EIS4.</string>
</dict>
</plist>
PLIST

        codesign --force --deep --sign - "$APP"
        echo "==> $APP"
        ;;

    Linux)
        echo "==> Generating PNGs"
        for size in 16 32 48 64 128 256 512; do
            mkdir -p "assets/icons/${size}x${size}"
            render_svg "$SVG" "$size" "assets/icons/${size}x${size}/cue.png"
        done

        echo "==> cargo build --release"
        cargo build --release

        echo "==> Creating package"
        PKG="target/release/cue-linux"
        rm -rf "$PKG"
        mkdir -p "$PKG"
        cp target/release/$BIN "$PKG/"

        for size in 16 32 48 64 128 256 512; do
            mkdir -p "$PKG/icons/hicolor/${size}x${size}/apps"
            cp "assets/icons/${size}x${size}/cue.png" "$PKG/icons/hicolor/${size}x${size}/apps/"
        done

        cat > "$PKG/cue.desktop" << DESKTOP
[Desktop Entry]
Name=Cue
Comment=EIS4 Electrochemical Instrument
Exec=cue
Icon=cue
Terminal=false
Type=Application
Categories=Science;Education;
DESKTOP

        cat > "$PKG/install.sh" << 'INSTALL'
#!/bin/bash
set -e
PREFIX="${1:-/usr/local}"
install -Dm755 cue "$PREFIX/bin/cue"
install -Dm644 cue.desktop "$PREFIX/share/applications/cue.desktop"
for d in icons/hicolor/*/apps; do
    size="$(basename "$(dirname "$d")")"
    install -Dm644 "$d/cue.png" "$PREFIX/share/icons/hicolor/$size/apps/cue.png"
done
echo "Installed to $PREFIX"
INSTALL
        chmod +x "$PKG/install.sh"

        echo "==> $PKG/"
        ;;

    MINGW*|MSYS*|CYGWIN*)
        echo "==> Generating .ico"
        TMPICO=$(mktemp -d)
        for size in 16 32 48 64 128 256; do
            render_svg "$SVG" "$size" "$TMPICO/${size}.png"
        done
        magick "$TMPICO/16.png" "$TMPICO/32.png" "$TMPICO/48.png" \
               "$TMPICO/64.png" "$TMPICO/128.png" "$TMPICO/256.png" assets/cue.ico
        rm -rf "$TMPICO"

        echo "==> cargo build --release"
        cargo build --release

        echo "==> target/release/cue.exe (icon embedded via build.rs)"
        ;;

    *)
        echo "Unknown platform: $(uname -s)"
        cargo build --release
        ;;
esac
