#!/usr/bin/env bash
# Installs the latest build of Notes for Linux/x86_64. No root required.
#
#   curl -fsSL https://notes.sijanpaudel.com.np/install.sh | bash
#
# Safe to re-run: it always re-fetches whatever scripts/release.sh most
# recently published, so running this again is how you upgrade.

set -euo pipefail

MANIFEST_URL="https://yvakjiv0v37eg5xc.public.blob.vercel-storage.com/notes/latest.json"
ICON_URL="https://notes.sijanpaudel.com.np/icon.png"
INSTALL_DIR="$HOME/.local/share/notes"
BIN_DIR="$HOME/.local/bin"
DESKTOP_DIR="$HOME/.local/share/applications"

log() { printf '%s\n' "$*"; }
die() { printf 'Error: %s\n' "$*" >&2; exit 1; }

[ "$(uname -s)" = "Linux" ] || die "Notes only supports Linux right now."
[ "$(uname -m)" = "x86_64" ] || die "Notes only publishes x86_64 builds right now (detected $(uname -m))."
command -v curl >/dev/null 2>&1 || die "curl is required but not found."

log "Fetching latest release info..."
manifest_json="$(curl -fsSL "$MANIFEST_URL")" \
  || die "Could not reach the release manifest. Check your connection and try again."

version="$(printf '%s' "$manifest_json" | grep -m1 '"version"' | sed -E 's/.*"version":[[:space:]]*"([^"]+)".*/\1/')"
appimage_url="$(printf '%s' "$manifest_json" | grep -m1 '"appimage_url"' | sed -E 's/.*"appimage_url":[[:space:]]*"([^"]+)".*/\1/')"

[ -n "$version" ] && [ -n "$appimage_url" ] || die "No published release found."

log "Installing Notes $version..."
mkdir -p "$INSTALL_DIR" "$BIN_DIR" "$DESKTOP_DIR"

# Downloads to a temp file and renames it into place afterward, rather
# than writing directly to Notes.AppImage — a rename is atomic and works
# even while an old copy at that path is currently running (Linux allows
# replacing a file that's open/executing; whoever already has it open
# just keeps using the old inode). Writing straight into the live path
# instead risks ETXTBSY ("text file busy") if Notes happens to be running
# during a re-install/upgrade, or — worse — leaves a half-downloaded,
# permanently execution-blocked file behind if this script gets
# interrupted (Ctrl+C, closed terminal, dropped connection) partway
# through, since curl would still be holding it open for writing.
curl -fsSL "$appimage_url" -o "$INSTALL_DIR/Notes.AppImage.download" || die "Download failed."
chmod +x "$INSTALL_DIR/Notes.AppImage.download"
mv -f "$INSTALL_DIR/Notes.AppImage.download" "$INSTALL_DIR/Notes.AppImage"
curl -fsSL "$ICON_URL" -o "$INSTALL_DIR/icon.png" 2>/dev/null || true

# Extracted once here rather than relying on FUSE-mounting the AppImage at
# every launch. Chromium memory-maps large resource files straight out of
# wherever it's running from — when that's a live FUSE mount of the
# squashfs, an unstable mount (which FUSE mounts can become, especially
# after a prior instance was force-killed rather than exited cleanly)
# causes hard SIGBUS crashes with zero error output: the app just never
# appears, no window, nothing in the process list a moment later. This
# extracts once (trading ~300MB disk for it) so normal launches never
# touch FUSE at all — matching how the plain-extracted .rpm build has
# behaved reliably by comparison.
log "Extracting (so normal launches don't depend on FUSE)..."
rm -rf "$INSTALL_DIR/app" "$INSTALL_DIR/squashfs-root"
if (cd "$INSTALL_DIR" && "$INSTALL_DIR/Notes.AppImage" --appimage-extract >/dev/null 2>&1); then
  mv "$INSTALL_DIR/squashfs-root" "$INSTALL_DIR/app"
  RUN_TARGET="$INSTALL_DIR/app/AppRun"
else
  log "Extraction failed — falling back to running the AppImage directly (needs FUSE)."
  RUN_TARGET="$INSTALL_DIR/Notes.AppImage"
fi

cat > "$BIN_DIR/notes" <<LAUNCHER
#!/usr/bin/env bash
exec "$RUN_TARGET" "\$@"
LAUNCHER
chmod +x "$BIN_DIR/notes"

cat > "$DESKTOP_DIR/notes.desktop" <<DESKTOP
[Desktop Entry]
Type=Application
Name=Notes
Comment=Local practice-interview overlay
Exec=$RUN_TARGET
Icon=$INSTALL_DIR/icon.png
Terminal=false
Categories=Utility;
StartupWMClass=notes
DESKTOP

command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$DESKTOP_DIR" >/dev/null 2>&1 || true

log ""
log "Notes $version installed."
log "Run it with: notes"
log "Or find \"Notes\" in your Applications menu."

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *)
    log ""
    log "Note: $BIN_DIR isn't on your PATH yet. Add this to your shell profile:"
    log "  export PATH=\"\$HOME/.local/bin:\$PATH\""
    ;;
esac

if [ "$RUN_TARGET" = "$INSTALL_DIR/Notes.AppImage" ]; then
  log ""
  log "If the app window doesn't launch, your system may be missing FUSE."
  log "Try instead: $INSTALL_DIR/Notes.AppImage --appimage-extract-and-run"
fi
