#!/bin/sh
# FileVolley installer for macOS and Linux.
#
#   curl -fsSL https://filevolley.jefbuilds.dev/install.sh | sh
#
# Downloads the newest FileVolley Desktop from GitHub releases
# (https://github.com/jedgarf/FileVolley-Releases), checks its SHA-256 against the
# published one, and installs it:
#   macOS   FileVolley.app into /Applications (or ~/Applications)
#   Linux   the .deb on Debian/Ubuntu (x64), otherwise the AppImage in your home folder
#
# Options, as environment variables (put them before "sh": ... | FILEVOLLEY_FORMAT=appimage sh):
#   FILEVOLLEY_FORMAT=appimage   on Debian/Ubuntu, install the AppImage instead of the .deb
#
# Everything sits inside main(), so a download cut short never runs half a script.

set -eu

SITE="${FILEVOLLEY_SITE:-https://filevolley.jefbuilds.dev}"

bold() { printf '\033[1m%s\033[0m\n' "$*"; }
info() { printf '  %s\n' "$*"; }
fail() {
  printf '\033[31mError:\033[0m %s\n' "$*" >&2
  exit 1
}
has() { command -v "$1" >/dev/null 2>&1; }

fetch() { # fetch URL [FILE]: to FILE, or to stdout
  if has curl; then
    if [ $# -gt 1 ]; then curl -fL --progress-bar -o "$2" "$1"; else curl -fsSL "$1"; fi
  elif has wget; then
    if [ $# -gt 1 ]; then wget -q --show-progress -O "$2" "$1"; else wget -qO- "$1"; fi
  else
    fail "curl or wget is needed to download FileVolley."
  fi
}

sha256_of() {
  if has sha256sum; then
    sha256sum "$1" | cut -d' ' -f1
  elif has shasum; then
    shasum -a 256 "$1" | cut -d' ' -f1
  else
    fail "sha256sum or shasum is needed to check the download."
  fi
}

# Downloads the newest file for platform $1 into $TMP and checks it. Sets FILE and VERSION.
download() {
  meta="$(fetch "$SITE/api/install/$1")" || fail "Couldn't reach $SITE to find the newest version."
  VERSION="$(printf '%s\n' "$meta" | sed -n 's/^version=//p')"
  name="$(printf '%s\n' "$meta" | sed -n 's/^name=//p')"
  url="$(printf '%s\n' "$meta" | sed -n 's/^url=//p')"
  sha="$(printf '%s\n' "$meta" | sed -n 's/^sha256=//p')"
  [ -n "$url" ] && [ -n "$name" ] || fail "No FileVolley download found for $1."
  [ -n "$sha" ] || fail "The release has no published checksum for $name, so it wasn't installed."

  bold "Downloading FileVolley $VERSION ($name)"
  FILE="$TMP/$name"
  fetch "$url" "$FILE" || fail "The download failed."
  [ "$(sha256_of "$FILE")" = "$sha" ] || fail "The download didn't match the published checksum, so it wasn't installed."
  info "Checksum verified."
}

install_mac() {
  if [ "$(uname -m)" = "arm64" ] || [ "$(sysctl -n hw.optional.arm64 2>/dev/null || echo 0)" = "1" ]; then
    download mac-arm64
  else
    download mac-x64
  fi

  dest="${FILEVOLLEY_APP_DIR:-/Applications}"
  if [ -z "${FILEVOLLEY_APP_DIR:-}" ] && [ ! -w "$dest" ]; then
    dest="$HOME/Applications"
  fi
  mkdir -p "$dest"

  if [ -d "$dest/FileVolley.app" ] && pgrep -xq FileVolley 2>/dev/null; then
    info "Closing FileVolley to replace it…"
    osascript -e 'quit app "FileVolley"' >/dev/null 2>&1 || true
    sleep 2
  fi

  bold "Installing into $dest"
  mnt="$TMP/mnt"
  mkdir -p "$mnt"
  hdiutil attach -nobrowse -readonly -noautoopen -quiet -mountpoint "$mnt" "$FILE" || fail "Couldn't open the disk image."
  app="$(find "$mnt" -maxdepth 1 -name '*.app' | head -n 1)"
  if [ -z "$app" ]; then
    hdiutil detach -quiet "$mnt" || true
    fail "No app found in the disk image."
  fi
  rm -rf "$dest/FileVolley.app"
  ditto "$app" "$dest/FileVolley.app"
  hdiutil detach -quiet "$mnt" || true
  rmdir "$mnt" 2>/dev/null || true

  echo
  bold "FileVolley $VERSION is installed."
  info "Open it from $dest, Launchpad or Spotlight."
  info "Updates arrive inside the app (Settings › Updates)."
}

install_linux() {
  case "$(uname -m)" in
    x86_64 | amd64) arch=x64 ;;
    aarch64 | arm64) arch=arm64 ;;
    *) fail "FileVolley runs on 64-bit x86 or ARM; this machine is $(uname -m)." ;;
  esac

  if [ "$arch" = x64 ] && [ "${FILEVOLLEY_FORMAT:-}" != appimage ] && has apt-get && has dpkg; then
    install_deb
  else
    install_appimage "$arch"
  fi
}

install_deb() {
  download linux-deb
  # apt reads the file as its own user: make it readable so it doesn't complain.
  chmod 755 "$TMP"
  chmod 644 "$FILE"
  bold "Installing the .deb package (asks for your password)"
  if [ "$(id -u)" -eq 0 ]; then
    apt-get install -y "$FILE"
  elif has sudo; then
    sudo apt-get install -y "$FILE"
  else
    fail "Installing the .deb needs root. Run this as root, or use FILEVOLLEY_FORMAT=appimage."
  fi

  echo
  bold "FileVolley $VERSION is installed."
  info "Open it from your app menu, or run: filevolley-desktop"
  info "Updates arrive inside the app (Settings › Updates)."
}

install_appimage() {
  download "linux-$1"
  data="${XDG_DATA_HOME:-$HOME/.local/share}"
  dir="$data/filevolley"
  bin="$HOME/.local/bin"
  mkdir -p "$dir" "$bin" "$data/applications" "$data/icons/hicolor/512x512/apps"

  bold "Installing into $dir"
  # Copied next to the old one first, so the switch is a single rename.
  cp "$FILE" "$dir/.FileVolley.AppImage.new"
  chmod 755 "$dir/.FileVolley.AppImage.new"
  mv -f "$dir/.FileVolley.AppImage.new" "$dir/FileVolley.AppImage"

  # A wrapper, not a symlink: the AppImage then always knows its real path, which
  # its in-app updater replaces.
  printf '#!/bin/sh\nexec "%s" "$@"\n' "$dir/FileVolley.AppImage" >"$bin/filevolley"
  chmod 755 "$bin/filevolley"

  fetch "$SITE/brand/icon-512.png" "$data/icons/hicolor/512x512/apps/filevolley.png" 2>/dev/null || true
  cat >"$data/applications/filevolley.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=FileVolley
Comment=Send files between your computers and phones over Wi-Fi
Exec="$dir/FileVolley.AppImage" %U
Icon=filevolley
Terminal=false
Categories=Network;FileTransfer;Utility;
StartupWMClass=FileVolley
EOF
  has update-desktop-database && update-desktop-database "$data/applications" >/dev/null 2>&1 || true

  echo
  bold "FileVolley $VERSION is installed."
  info "Open it from your app menu, or run: filevolley"
  case ":$PATH:" in
    *":$bin:"*) ;;
    *) info "(To run \"filevolley\" from a terminal, add $bin to your PATH.)" ;;
  esac
  if has ldconfig && ! ldconfig -p 2>/dev/null | grep -q 'libfuse\.so\.2'; then
    info "AppImages need FUSE 2. If FileVolley doesn't open, install it:"
    info "  Ubuntu 24.04+: sudo apt install libfuse2t64    Older Ubuntu/Debian: sudo apt install libfuse2"
  fi
  info "Updates arrive inside the app (Settings › Updates)."
}

cleanup() {
  if [ -d "$TMP/mnt" ] && has hdiutil; then hdiutil detach -quiet "$TMP/mnt" 2>/dev/null || true; fi
  rm -rf "$TMP"
}

main() {
  TMP="$(mktemp -d 2>/dev/null || mktemp -d -t filevolley)"
  trap cleanup EXIT INT TERM

  case "$(uname -s)" in
    Darwin) install_mac ;;
    Linux) install_linux ;;
    *) fail "This installer is for macOS and Linux. On Windows, download the installer from https://filevolley.jefbuilds.dev" ;;
  esac
}

main "$@"
