#!/usr/bin/env bash
# TelMusic per-user installer. Download, verify, then extract without FUSE.
set -euo pipefail

artifact_url='https://telmusic.app/downloads/1.0.0+26428/telmusic-1.0.0+26428-linux-x64.AppImage'
artifact_sha256='c05b2c955c3891896ec9bbdc8e74389ece369af05d77c30f62c78353faeadb65'
release_version='1.0.0'

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

main() {
  case "${1:-}" in
    --help)
      printf 'Install: curl -fsSL https://telmusic.app/install.sh | bash\nUninstall: curl -fsSL https://telmusic.app/install.sh | bash -s -- --uninstall\nRequires x86_64 desktop Linux with glibc 2.35+, EGL/GLES2 graphics drivers, X11 or XWayland.\n'
      return ;;
    ''|--uninstall) ;;
    *) die "Unknown option: $1 (use --help)" ;;
  esac
  [ "$#" -le 1 ] || die 'Too many arguments.'
  [ "$(id -u)" != 0 ] || die 'Run as your desktop user, without sudo.'
  data_dir="${XDG_DATA_HOME:-$HOME/.local/share}"
  install_root="$data_dir/telmusic-installer"
  launcher="$HOME/.local/bin/telmusic"
  desktop="$data_dir/applications/app.telmusic.telmusic.desktop"
  icon="$data_dir/icons/hicolor/scalable/apps/app.telmusic.telmusic.svg"
  for command in flock mktemp; do command -v "$command" >/dev/null || die "Required command is missing: $command"; done
  umask 077
  mkdir -p "$install_root"
  exec 9>"$install_root/.install.lock"
  flock 9
  if [ "${1:-}" = --uninstall ]; then
    # Leave application data, downloads, settings and sign-in untouched.
    if [ -f "$launcher" ] && grep -q '^# TelMusic AppImage launcher$' "$launcher"; then rm -f "$launcher"; fi
    if [ -f "$desktop" ] && grep -q '^X-TelMusic-Installer=true$' "$desktop"; then rm -f "$desktop" "$icon"; fi
    rm -f "$install_root/current"
    rm -rf "$install_root/versions"
    printf 'TelMusic removed. Your application data has been kept.\n'
    return
  fi
  [ "$(uname -s)" = Linux ] && [ "$(uname -m)" = x86_64 ] || die 'This release supports x86_64 Linux only.'
  libc="$(getconf GNU_LIBC_VERSION 2>/dev/null)" || die 'glibc Linux is required; musl/Alpine is not supported.'
  case "$libc" in
    'glibc '*) libc="${libc#glibc }" ;;
    *) die 'glibc Linux is required; musl/Alpine is not supported.' ;;
  esac
  [ "$(printf '%s\n' 2.35 "$libc" | sort -V | head -n1)" = 2.35 ] || die 'glibc 2.35 or newer is required.'
  for command in curl sha256sum; do command -v "$command" >/dev/null || die "Required command is missing: $command"; done
  if [ -e "$launcher" ] || [ -L "$launcher" ]; then
    [ -f "$launcher" ] && grep -q '^# TelMusic AppImage launcher$' "$launcher" || die "An unrelated launcher already exists at $launcher; move it first."
  fi
  version_root="$install_root/versions/$artifact_sha256"
  mkdir -p "$install_root/versions"
  stage="$(mktemp -d "$install_root/.install.XXXXXX")"
  trap 'rm -rf "$stage"' EXIT
  if [ ! -x "$version_root/AppRun" ]; then
    printf 'Downloading TelMusic %s...\n' "$release_version"
    curl --fail --location --retry 3 --connect-timeout 20 \
      --proto '=https' --proto-redir '=https' "$artifact_url" -o "$stage/TelMusic.AppImage"
    printf '%s  %s\n' "$artifact_sha256" "$stage/TelMusic.AppImage" | sha256sum --check --status || die 'Checksum mismatch; the existing installation was kept.'
    chmod +x "$stage/TelMusic.AppImage"
    if ! (cd "$stage" && ./TelMusic.AppImage --appimage-extract >extract.log 2>&1); then
      cat "$stage/extract.log" >&2
      die 'Could not extract the AppImage; the existing installation was kept.'
    fi
    [ -x "$stage/squashfs-root/AppRun" ] || die 'Invalid AppImage: AppRun is missing.'
    [ -f "$stage/squashfs-root/app.telmusic.telmusic.svg" ] || die 'Invalid AppImage: icon is missing.'
    mv "$stage/squashfs-root" "$version_root"
  fi
  mkdir -p "$(dirname "$launcher")" "$(dirname "$desktop")" "$(dirname "$icon")"
  printf '#!/usr/bin/env bash\n# TelMusic AppImage launcher\nexport APPDIR="$(readlink -f %q)"\nexec "$APPDIR/AppRun" "$@"\n' "$install_root/current" >"$stage/launcher"
  chmod +x "$stage/launcher"
  desktop_exec="${launcher//\\/\\\\}"
  desktop_exec="${desktop_exec//\"/\\\"}"
  desktop_exec="${desktop_exec//\$/\\\$}"
  desktop_exec="${desktop_exec//\`/\\\`}"
  cat >"$stage/desktop" <<EOF
[Desktop Entry]
Type=Application
Name=TelMusic
Comment=Private player for media in your Telegram chats
Exec="$desktop_exec" %u
Icon=app.telmusic.telmusic
Terminal=false
MimeType=x-scheme-handler/telmusic;
Categories=AudioVideo;Audio;Player;
StartupWMClass=telmusic
X-TelMusic-Installer=true
EOF
  cp "$version_root/app.telmusic.telmusic.svg" "$icon"
  mv -f "$stage/launcher" "$launcher"
  mv -f "$stage/desktop" "$desktop"
  ln -s "$version_root" "$stage/current"
  mv -Tf "$stage/current" "$install_root/current"
  command -v update-desktop-database >/dev/null && update-desktop-database "$data_dir/applications" 2>/dev/null || true
  printf 'TelMusic %s is installed. Open TelMusic from your applications menu.\nRun from a terminal: %s\n' "$release_version" "$launcher"
}

# Parse the entire final block before executing, including when piped from curl.
{
  main "$@"
}
