#!/bin/bash
# Flow macOS installer — downloads the latest .dmg, mounts, copies to
# /Applications, and removes quarantine attributes.
#
# The script is release-invariant: the version is resolved by the
# server — /downloads/latest/macos-arm64 redirects to the concrete
# .dmg. It never needs a version bump in a release.
#
# Run in Terminal:
#   bash <(curl -fsSL https://flowdj.app/scripts/install-macos.sh)
set -e

APP_NAME="Flow"
BASE="https://flowdj.app"
LATEST_URL="${BASE}/downloads/latest/macos-arm64"

# Resolve the current release server-side: the endpoint 302s to the
# concrete .dmg. One HEAD probe transfers no bytes and is not recorded
# in download stats; the artifact GET below is the recorded event.
DMG_NAME="$(curl -fsIL -o /dev/null -w '%{url_effective}' "$LATEST_URL" | xargs basename 2>/dev/null || true)"
if [[ ! "$DMG_NAME" =~ ^Flow-[0-9]+\.[0-9]+\.[0-9]+-macos-arm64\.dmg$ ]]; then
  echo "Error: cannot resolve the latest version (server unreachable?)" >&2
  exit 1
fi
URL="${BASE}/downloads/${DMG_NAME}"
VER="$(echo "$DMG_NAME" | sed -E 's/^Flow-([0-9]+\.[0-9]+\.[0-9]+)-macos-arm64\.dmg$/\1/')"
DEST="/tmp/${DMG_NAME}"

# ── ASCII art ──────────────────────────────────────────────────────────
cat <<'ART'

  #############+  +***=                =*#%%%%#*+     =###=      ####=      ###*
  @@@@@@@@@@@@@=  =@@@#              #@@@@@@@@@@@%=   +@@@%     #@@@@@     *@@@*
  @@@%+++++++++   =@@@*            +@@@@#=   +*%@@@#   #@@@+    @@@@@@*    %@@%
  @@@%            =@@@*            @@@@=        #@@@*  =@@@*   *@@%%@@%   +@@@*
  @@@%            =@@@*           =@@@#          @@@%   %@@%   @@@*+@@@=  #@@@
  @@@@@@@@@@@@    =@@@*           #@@@=          %@@@   *@@@= *@@@  %@@#  @@@#
  @@@@%%%%%%%%    =@@@*           #@@@=          %@@@    @@@# %@@#  =@@@ =@@@=
  @@@%            =@@@*           *@@@#         +@@@%    #@@%*@@@    %@@*#@@%
  @@@%            =@@@*            @@@@=        %@@@*    +@@@@@@#    =@@@@@@*
  @@@%            =@@@#+++++++++   +@@@@#=   +*%@@@#      %@@@@@+     @@@@@@
  @@@@            =@@@@@@@@@@@@@=    #@@@@@@@@@@@%=       *@@@@%      *@@@@#
  ###*            +#############+      =*#%%%%#*+          ####+       ####
ART

echo ""
printf '\033[1m  Flow %s — the file browser, for DJs.\033[0m\n' "$VER"
echo ""
echo "  This script downloads the official Flow .dmg, mounts it, copies the"
echo "  app to /Applications, and strips macOS quarantine attributes so it"
echo "  launches without Gatekeeper prompts. No separate installs, no"
echo "  dependencies — everything Flow needs is bundled inside the app."
echo ""

# ── Helpers ───────────────────────────────────────────────────────────

# print_step "Doing X..." → prints a 36-char left-justified label; caller
# completes it with "done" via finish_step.
print_step() { printf '  \033[1m→\033[0m %-36s ' "$1"; }
finish_step() { printf '\033[32mdone\033[0m\n'; }

# mount_dmg <dmg> — attaches the image without opening a Finder window and
# prints the mount table. `diskutil image attach` is the current spelling;
# `hdiutil attach` is deprecated and prints a warning into the user's
# terminal, so it stays only as the fallback for systems without the new
# verb. Both print the same tab-separated rows, so the caller parses
# /Volumes/ alike.
mount_dmg() {
  diskutil image attach --mountOptions nobrowse "$1" 2>/dev/null ||
    hdiutil attach "$1" -nobrowse
}

# unmount_dmg <mount-point> — ejects the mounted image. `hdiutil detach`
# still works but macOS labels it deprecated and prints a warning on every
# run, straight into the user's terminal; `diskutil eject` is the supported
# spelling. detach stays as the fallback for old systems.
unmount_dmg() {
  diskutil eject "$1" >/dev/null 2>&1 || hdiutil detach "$1" >/dev/null
}

# progress_bar <current> <total>
# Renders a single-line ASCII progress bar (40 chars wide) to stderr so it
# doesn't interfere with stdout piping.
progress_bar() {
  local cur="$1" total="$2"
  local width=40
  local pct=$(( cur * 100 / total ))
  local filled=$(( cur * width / total ))
  local i
  local bar=""
  for (( i=0; i<filled; i++ )); do bar+="█"; done
  for (( i=filled; i<width; i++ )); do bar+="░"; done
  # Human-readable sizes (MB)
  local cur_mb cur_dec
  cur_mb=$(( cur / 1048576 ))
  cur_dec=$(( (cur % 1048576) * 10 / 1048576 ))
  local total_mb total_dec
  total_mb=$(( total / 1048576 ))
  total_dec=$(( (total % 1048576) * 10 / 1048576 ))
  printf '\r  [%s] %d.%d MB / %d.%d MB  %3d%%' "$bar" "$cur_mb" "$cur_dec" "$total_mb" "$total_dec" "$pct"
}

# download <url> <dest> — downloads with a custom progress bar, hiding
# curl's default output. Uses curl -f -s -S (silent, show errors) and
# writes progress to a temp file that we parse line-by-line.
download() {
  local url="$1" dest="$2"
  # Get total size from the server (Content-Length header).
  local total
  total=$(curl -sI "$url" | tr -d '\r' | awk -F': ' 'tolower($1)=="content-length"{print $2}' | tail -1)
  if [[ -z "$total" || "$total" == "0" ]]; then
    # Fallback: no Content-Length — just use curl's own progress.
    echo "  (unknown size, downloading...)"
    curl -fL -o "$dest" "$url"
    return
  fi
  # Download with curl --progress-bar, capturing its # bar to /dev/null.
  # We poll the local file size for our own bar.
  curl -fsL -o "$dest" "$url" &
  local pid=$!
  local last_size=0
  while kill -0 "$pid" 2>/dev/null; do
    local size=0
    [[ -f "$dest" ]] && size=$(stat -f%z "$dest" 2>/dev/null || echo 0)
    if (( size > last_size )); then
      progress_bar "$size" "$total"
      last_size=$size
    fi
    sleep 0.15
  done
  wait "$pid"
  # Final 100% render.
  progress_bar "$total" "$total"
  echo ""
}

# ── Quit running instance ─────────────────────────────────────────────
if pgrep -f "Flow.app" >/dev/null 2>&1; then
  print_step "Quitting running $APP_NAME..."
  osascript -e 'tell application id "com.uoziod.flow" to quit' 2>/dev/null || true
  for i in $(seq 1 10); do
    pgrep -f "Flow.app" >/dev/null 2>&1 || break
    sleep 1
  done
  pkill -9 -f "Flow.app" 2>/dev/null || true
  finish_step
fi

# ── Download ──────────────────────────────────────────────────────────
echo "  Downloading $DMG_NAME"
download "$URL" "$DEST"

# ── Mount ──────────────────────────────────────────────────────────────
print_step "Mounting DMG..."
MOUNT=$(mount_dmg "$DEST" | grep '/Volumes/' | sed 's/.*\(\/Volumes\/.*\)/\1/' | xargs)
APP=$(find "$MOUNT" -name "*.app" -maxdepth 1 | head -1)
if [ -z "$APP" ]; then
  echo "Error: no .app found in DMG" >&2
  unmount_dmg "$MOUNT"
  rm "$DEST"
  exit 1
fi
finish_step

# ── Remove existing app ────────────────────────────────────────────────
print_step "Removing existing app..."
if [ -d "/Applications/$APP_NAME.app" ]; then
  if [ -w "/Applications/$APP_NAME.app" ]; then
    rm -rf "/Applications/$APP_NAME.app"
  else
    osascript -e "do shell script \"rm -rf '/Applications/$APP_NAME.app'\" with administrator privileges"
  fi
fi
finish_step

# ── Copy to /Applications ─────────────────────────────────────────────
print_step "Copying to /Applications..."
if [ -w "/Applications" ]; then
  cp -R "$APP" "/Applications/$APP_NAME.app"
else
  osascript -e "do shell script \"cp -R '$APP' '/Applications/$APP_NAME.app'\" with administrator privileges"
fi
finish_step

# ── Remove quarantine ──────────────────────────────────────────────────
print_step "Removing quarantine attributes..."
xattr -cr "/Applications/$APP_NAME.app" 2>/dev/null || \
  osascript -e "do shell script \"xattr -cr '/Applications/$APP_NAME.app'\" with administrator privileges"
finish_step

# ── Unmount ────────────────────────────────────────────────────────────
print_step "Unmounting DMG..."
unmount_dmg "$MOUNT"
rm "$DEST"
finish_step

# ── Done ───────────────────────────────────────────────────────────────
echo ""
printf '\033[1m  Done! Flow installed to /Applications/%s.app\033[0m\n' "$APP_NAME"
echo "  Launch: open /Applications/$APP_NAME.app"