#!/bin/bash
# Flow Linux installer — downloads the latest .AppImage, makes it
# executable, and moves it to ~/.local/bin/flow.
#
# The script is release-invariant: the version is resolved by the
# server — /downloads/latest/linux-x64 redirects to the concrete
# .AppImage. It never needs a version bump in a release.
#
# Run in Terminal:
#   bash <(curl -fsSL https://flowdj.app/scripts/install-linux.sh)
set -e

BASE="https://flowdj.app"
LATEST_URL="${BASE}/downloads/latest/linux-x64"

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

# ── 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 AppImage, makes it executable,"
echo "  and installs it to ~/.local/bin/flow. No separate installs, no"
echo "  dependencies — everything Flow needs is bundled inside the AppImage."
echo ""

# ── Helpers ───────────────────────────────────────────────────────────
print_step() { printf '  \033[1m→\033[0m %-36s ' "$1"; }
finish_step() { printf '\033[32mdone\033[0m\n'; }

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
  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() {
  local url="$1" dest="$2"
  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
    echo "  (unknown size, downloading...)"
    curl -fL -o "$dest" "$url"
    return
  fi
  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 -c%s "$dest" 2>/dev/null || 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"
  progress_bar "$total" "$total"
  echo ""
}

# ── Prepare ────────────────────────────────────────────────────────────
print_step "Creating install directory..."
mkdir -p "$INSTALL_DIR"
finish_step

# ── Download ───────────────────────────────────────────────────────────
echo "  Downloading ${FILENAME}"
download "$URL" "$TMP"

# ── Install ─────────────────────────────────────────────────────────────
print_step "Installing to ${DEST}..."
mv -f "$TMP" "$DEST"
chmod +x "$DEST"
finish_step

# ── PATH ────────────────────────────────────────────────────────────────
update_path() {
  local shell_rc="$1"
  local marker="# Flow: ensure ~/.local/bin in PATH"
  if [ -f "$shell_rc" ] && ! grep -q "$marker" "$shell_rc"; then
    printf '\n%s\n[ -d "${HOME}/.local/bin" ] && export PATH="${HOME}/.local/bin:${PATH}"\n' "$marker" >> "$shell_rc"
    echo "  Added ~/.local/bin to PATH in $shell_rc"
  fi
}

print_step "Ensuring ~/.local/bin is in PATH..."
update_path "${HOME}/.bashrc"
update_path "${HOME}/.zshrc"
finish_step

# ── Done ────────────────────────────────────────────────────────────────
echo ""
printf '\033[1m  Flow installed to %s\033[0m\n' "$DEST"
echo "  Run 'flow' from a terminal (restart shell if 'command not found')."