#!/usr/bin/env bash
set -euo pipefail

APP_NAME="DevHub.app"
ZIP_NAME='devhub-arm64.app.zip'
ZIP_MD5='669a862a3d5145bb9063ebd012cc5005'
DOWNLOAD_BASE_URL=${DOWNLOAD_BASE_URL:-'https://tools.leoustc.com'}
INSTALL_DIR=${INSTALL_DIR:-/Applications}
WORK_DIR=${WORK_DIR:-$(mktemp -d "${TMPDIR:-/tmp}/devhub-install.XXXXXX")}

cleanup() {
  if [[ "${KEEP_WORK_DIR:-0}" != "1" ]]; then
    rm -rf "$WORK_DIR"
  fi
}
trap cleanup EXIT

md5_file() {
  if command -v md5sum >/dev/null 2>&1; then
    md5sum "$1" | awk '{print $1}'
  elif command -v md5 >/dev/null 2>&1; then
    md5 -q "$1"
  else
    echo "md5 tool not found (need md5sum or md5)" >&2
    exit 1
  fi
}

download_file() {
  local name="$1"
  local url="${DOWNLOAD_BASE_URL%/}/$name"
  echo "Downloading $url"
  curl -fL --retry 3 --retry-delay 2 -o "$WORK_DIR/$name" "$url"
}

PARTS=(
  'devhub-arm64.app.zip.part-00'
  'devhub-arm64.app.zip.part-01'
  'devhub-arm64.app.zip.part-02'
  'devhub-arm64.app.zip.part-03'
)

if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
  echo "Usage: curl -sS https://tools.leoustc.com/install_devhub.sh | bash"
  echo "Optional: DOWNLOAD_BASE_URL=https://host/path INSTALL_DIR=/Applications bash install_devhub.sh"
  echo "Downloads DevHub split zip parts, reconstructs the zip, unzips it, and installs DevHub.app."
  exit 0
fi

mkdir -p "$WORK_DIR"
cd "$WORK_DIR"

for part in "${PARTS[@]}"; do
  download_file "$part"
done

echo "Reconstructing $ZIP_NAME"
cat "${PARTS[@]}" > "$ZIP_NAME"

actual_md5="$(md5_file "$ZIP_NAME")"
if [[ "$actual_md5" != "$ZIP_MD5" ]]; then
  echo "Checksum mismatch for $ZIP_NAME" >&2
  echo "expected: $ZIP_MD5" >&2
  echo "actual:   $actual_md5" >&2
  exit 1
fi

echo "Unzipping $ZIP_NAME"
unzip -q "$ZIP_NAME"

if [[ ! -d "$APP_NAME" ]]; then
  echo "Unzip did not produce $APP_NAME" >&2
  exit 1
fi

target="$INSTALL_DIR/$APP_NAME"
echo "Installing $APP_NAME to $target"
if [[ -w "$INSTALL_DIR" ]]; then
  rm -rf "$target"
  ditto "$APP_NAME" "$target"
else
  sudo rm -rf "$target"
  sudo ditto "$APP_NAME" "$target"
fi

xattr -cr "$target" 2>/dev/null || true
echo "Installed: $target"
echo "Open it with: open '$target'"
