#!/usr/bin/env bash
set -euo pipefail

APP_TEMPLATE="/usr/lib/stagefocusx"
DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
USER_ROOT="$DATA_HOME/stagefocusx"
USER_RUNTIME="$USER_ROOT/stagefocusx_runtime"

mkdir -p "$USER_ROOT"

if command -v xdg-mime >/dev/null 2>&1; then
  xdg-mime default stagefocusx.desktop x-scheme-handler/stagefocusx >/dev/null 2>&1 || true
fi

if command -v rsync >/dev/null 2>&1; then
  mkdir -p "$USER_RUNTIME"
  rsync -a \
    --exclude '__pycache__/' \
    --exclude '*.pyc' \
    --exclude 'library/***' \
    --exclude 'data/***' \
    "$APP_TEMPLATE/stagefocusx_runtime/" \
    "$USER_RUNTIME/"
else
  if [[ ! -d "$USER_RUNTIME" ]]; then
    cp -a "$APP_TEMPLATE/stagefocusx_runtime" "$USER_RUNTIME"
  fi
fi

mkdir -p \
  "$USER_RUNTIME/library" \
  "$USER_RUNTIME/data/backups" \
  "$USER_RUNTIME/data/coach_transfers" \
  "$USER_RUNTIME/data/exports" \
  "$USER_RUNTIME/data/logs"

if [[ ! -f "$USER_RUNTIME/data/studio_config.json" ]]; then
  mkdir -p "$USER_RUNTIME/data"
  cp "$APP_TEMPLATE/stagefocusx_runtime/data/studio_config.json" "$USER_RUNTIME/data/studio_config.json"
fi

cd "$USER_ROOT"
exec "$APP_TEMPLATE/sfx_flutter_app" "$@"
