#!/usr/bin/env bash

set -euo pipefail

if [[ $# -lt 2 ]]; then
    echo "Usage: $0 <source-png> <output-icns>"
    exit 1
fi

ICON_SRC="$1"
ICON_DEST="$2"

if [[ -f "$ICON_DEST" ]]; then
    exit 0
fi

if [[ ! -f "$ICON_SRC" ]]; then
    echo "[generate-mac-icon] Source icon not found: $ICON_SRC" >&2
    exit 1
fi

if ! command -v iconutil >/dev/null 2>&1; then
    echo "[generate-mac-icon] iconutil not found" >&2
    exit 1
fi

TMPDIR=$(mktemp -d)
ICONSET="$TMPDIR/AppIcon.iconset"
mkdir -p "$ICONSET"

for SIZE in 16 32 64 128 256 512; do
    sips -s format png "$ICON_SRC" --resampleHeightWidth $SIZE $SIZE --out "$ICONSET/icon_${SIZE}x${SIZE}.png" >/dev/null
    sips -s format png "$ICON_SRC" --resampleHeightWidth $((SIZE * 2)) $((SIZE * 2)) --out "$ICONSET/icon_${SIZE}x${SIZE}@2x.png" >/dev/null
done

iconutil -c icns "$ICONSET" -o "$ICON_DEST"
rm -rf "$TMPDIR"

if [[ -f "$ICON_DEST" ]]; then
    echo "[generate-mac-icon] Generated $ICON_DEST"
else
    echo "[generate-mac-icon] Failed to create $ICON_DEST" >&2
    exit 1
fi
