#!/bin/bash
set -euo pipefail

ELECTRON_VERSION="42.3.0"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
APP_ASAR="$SCRIPT_DIR/app.asar"
INSTALL_ROOT="$HOME/Applications"
APP_PATH="$INSTALL_ROOT/Your Desktop Pet.app"
WORK_DIR="$(mktemp -d)"

cleanup() {
  rm -rf "$WORK_DIR"
}
trap cleanup EXIT

if [[ ! -f "$APP_ASAR" ]]; then
  echo "The desktop pet application payload is missing."
  exit 1
fi

case "$(uname -m)" in
  arm64) ARCH="arm64" ;;
  x86_64) ARCH="x64" ;;
  *) echo "This Mac architecture is not supported."; exit 1 ;;
esac

ZIP_NAME="electron-v${ELECTRON_VERSION}-darwin-${ARCH}.zip"
URLS=(
  "https://github.com/electron/electron/releases/download/v${ELECTRON_VERSION}/${ZIP_NAME}"
  "https://npmmirror.com/mirrors/electron/${ELECTRON_VERSION}/${ZIP_NAME}"
)

for URL in "${URLS[@]}"; do
  if curl -fL --retry 2 "$URL" -o "$WORK_DIR/electron.zip"; then
    break
  fi
  rm -f "$WORK_DIR/electron.zip"
done

if [[ ! -f "$WORK_DIR/electron.zip" ]]; then
  echo "Could not download the desktop runtime. Check your internet connection and try again."
  exit 1
fi

ditto -x -k "$WORK_DIR/electron.zip" "$WORK_DIR/runtime"
mkdir -p "$INSTALL_ROOT"
rm -rf "$APP_PATH"
mv "$WORK_DIR/runtime/Electron.app" "$APP_PATH"
cp "$APP_ASAR" "$APP_PATH/Contents/Resources/app.asar"
rm -f "$APP_PATH/Contents/Resources/default_app.asar"

PLIST="$APP_PATH/Contents/Info.plist"
/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName Your Desktop Pet" "$PLIST"
/usr/libexec/PlistBuddy -c "Set :CFBundleName Your Desktop Pet" "$PLIST"
/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier com.yourdesktoppet.trial" "$PLIST"
mv "$APP_PATH/Contents/MacOS/Electron" "$APP_PATH/Contents/MacOS/Your Desktop Pet"
/usr/libexec/PlistBuddy -c "Set :CFBundleExecutable Your Desktop Pet" "$PLIST"

open "$APP_PATH"
echo "Installed to $APP_PATH"

