#!/bin/bash
set -euo pipefail

APP_NAME="SoundPM Folder Opener"
APP_PATH="$HOME/Applications/$APP_NAME.app"
ROOT_CONFIG="$HOME/Library/Application Support/SoundPMFolderOpener/allowed-root.txt"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SOURCE="$SCRIPT_DIR/SoundPMFolderOpener.swift"

if [[ "$(uname)" != "Darwin" ]]; then
  echo "Acest instalator rulează doar pe macOS." >&2
  exit 1
fi
if ! command -v swiftc >/dev/null; then
  echo "Lipsește Swift/Xcode Command Line Tools. Rulează mai întâi: xcode-select --install" >&2
  exit 1
fi
if [[ ! -f "$SOURCE" ]]; then
  if ! command -v curl >/dev/null; then
    echo "Lipsește $SOURCE și curl nu este disponibil pentru descărcare." >&2
    exit 1
  fi
  echo "Descarc sursa helperului macOS..."
  curl -fsSL "https://proiecte.alextruta.ro/tools/macos/SoundPMFolderOpener.swift" -o "$SOURCE"
fi

DEFAULT_ROOT="$HOME/Nextcloud"
read -r -p "Rădăcina locală Nextcloud [$DEFAULT_ROOT]: " NEXTCLOUD_ROOT
NEXTCLOUD_ROOT="${NEXTCLOUD_ROOT:-$DEFAULT_ROOT}"
if [[ ! -d "$NEXTCLOUD_ROOT" ]]; then
  echo "Folderul nu există: $NEXTCLOUD_ROOT" >&2
  exit 1
fi
NEXTCLOUD_ROOT="$(cd "$NEXTCLOUD_ROOT" && pwd -P)"

mkdir -p "$APP_PATH/Contents/MacOS" "$(dirname "$ROOT_CONFIG")"
printf '%s\n' "$NEXTCLOUD_ROOT" > "$ROOT_CONFIG"

cat > "$APP_PATH/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>CFBundleDevelopmentRegion</key><string>ro</string>
  <key>CFBundleDisplayName</key><string>SoundPM Folder Opener</string>
  <key>CFBundleExecutable</key><string>SoundPMFolderOpener</string>
  <key>CFBundleIdentifier</key><string>ro.alextruta.soundpm-folder-opener</string>
  <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
  <key>CFBundleName</key><string>SoundPM Folder Opener</string>
  <key>CFBundlePackageType</key><string>APPL</string>
  <key>CFBundleShortVersionString</key><string>1.0</string>
  <key>CFBundleVersion</key><string>1</string>
  <key>LSBackgroundOnly</key><true/>
  <key>CFBundleURLTypes</key><array><dict>
    <key>CFBundleURLName</key><string>SoundPM local folder</string>
    <key>CFBundleURLSchemes</key><array><string>soundpm-folder</string></array>
  </dict></array>
</dict></plist>
PLIST

swiftc "$SOURCE" -o "$APP_PATH/Contents/MacOS/SoundPMFolderOpener" -framework AppKit
chmod +x "$APP_PATH/Contents/MacOS/SoundPMFolderOpener"

LSREGISTER="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"
if [[ -x "$LSREGISTER" ]]; then "$LSREGISTER" -f "$APP_PATH"; fi
open "$APP_PATH"
echo "Instalat: $APP_PATH"
echo "Rădăcină autorizată: $NEXTCLOUD_ROOT"
echo "În SoundPM setează aceeași rădăcină la Setări → Foldere locale și Nextcloud."
