#!/bin/bash
# Builds the app on your desktop and starts it.
#
#   curl -fsSL https://<pages-url>/install.sh | bash -s -- https://<pages-url>/
#   bash install.sh .            # from a local copy of the repository
#
# Optional second argument picks the mode: subfolders (default) or system
# (Pictures, Movies, Music, Documents).
set -euo pipefail

APP_NAME="Homing"                # product name: change here and BRAND in app/index.html

BASE="${1:-}"
MODE="${2:-subfolders}"
DEST="${SORTER_DEST:-$HOME/Desktop}"
APP="$DEST/$APP_NAME.app"
FILES="sorter.py index.html AppIcon.icns"

fail() { echo "Error: $*" >&2; exit 1; }

[ -n "$BASE" ] || fail "missing the page address or a folder path. Copy the command from the install page."
BASE="${BASE%/}"
case "$MODE" in
  subfolders|podmape) MODE="subfolders" ;;
  system|sistem) MODE="system" ;;
  *) fail "unknown mode '$MODE' (subfolders or system)." ;;
esac
if [ "$(uname)" != "Darwin" ] && [ -z "${SORTER_SKIP_OS_CHECK:-}" ]; then
  fail "this tool only works on macOS."
fi

PY=""
for p in /opt/homebrew/bin/python3 /usr/local/bin/python3 /usr/bin/python3 "$(command -v python3 || true)"; do
  if [ -n "$p" ] && [ -x "$p" ] && "$p" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)' >/dev/null 2>&1; then
    PY="$p"; break
  fi
done
[ -n "$PY" ] || fail "Python 3 not found. Install it with 'xcode-select --install' and try again."

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
echo "Downloading files ..."
for f in $FILES; do
  if [ -d "$BASE" ]; then
    cat "$BASE/app/$f" > "$TMP/$f" || fail "missing $BASE/app/$f"
  else
    curl -fsSL "$BASE/app/$f" -o "$TMP/$f" || fail "could not download $BASE/app/$f"
  fi
done
"$PY" -m py_compile "$TMP/sorter.py" || fail "the downloaded script is not valid."
rm -rf "$TMP/__pycache__"

mkdir -p "$DEST"
rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
# cat instead of cp: the copy does not inherit the "downloaded from the internet" flag that makes macOS block it.
for f in $FILES; do cat "$TMP/$f" > "$APP/Contents/Resources/$f"; done
printf '%s\n' "$MODE" > "$APP/Contents/Resources/mode"

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>$APP_NAME</string>
  <key>CFBundleDisplayName</key><string>$APP_NAME</string>
  <key>CFBundleIdentifier</key><string>local.downloads-sorter</string>
  <key>CFBundleVersion</key><string>1</string>
  <key>CFBundleShortVersionString</key><string>1.0</string>
  <key>CFBundlePackageType</key><string>APPL</string>
  <key>CFBundleExecutable</key><string>launcher</string>
  <key>CFBundleIconFile</key><string>AppIcon</string>
  <key>LSUIElement</key><true/>
  <key>NSDownloadsFolderUsageDescription</key><string>Sorting the files in your Downloads folder.</string>
  <key>NSDocumentsFolderUsageDescription</key><string>Moving documents from Downloads into Documents.</string>
</dict>
</plist>
PLIST

cat > "$APP/Contents/MacOS/launcher" <<'LAUNCH'
#!/bin/bash
# Apps started from Finder do not have Homebrew on PATH, so look for Python ourselves.
RES="$(cd "$(dirname "$0")/../Resources" && pwd)"
PY=""
for p in /opt/homebrew/bin/python3 /usr/local/bin/python3 /usr/bin/python3; do
  if [ -x "$p" ]; then PY="$p"; break; fi
done
if [ -z "$PY" ]; then
  osascript -e 'display alert "Python 3 is missing" message "Install it with: xcode-select --install, then try again."'
  exit 1
fi
MODE="$(cat "$RES/mode" 2>/dev/null || echo subfolders)"
mkdir -p "$HOME/Library/Logs"
# The helper stops by itself 3 minutes after the page is closed. A second click on the icon just opens the page.
# -u: unbuffered, so the log keeps the output even when the helper is killed instead of exiting.
exec "$PY" -u "$RES/sorter.py" --mode "$MODE" --idle-exit 180 ${SORTER_ARGS:-} >> "$HOME/Library/Logs/downloads-sorter.log" 2>&1
LAUNCH
chmod +x "$APP/Contents/MacOS/launcher"

if command -v xattr >/dev/null 2>&1; then xattr -cr "$APP" || true; fi
touch "$APP"

echo "Installed: $APP"
echo "Mode: $MODE. To remove it, drag the icon to the Bin."
open "$APP" 2>/dev/null || echo "Open the app with a double click on its icon."
