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

readonly SWIFTFORMAT_VERSION="0.56.1"
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly BIN_DIR="$SCRIPT_DIR/.bin"
readonly SWIFTFORMAT_VERSION_STR="$(echo "$SWIFTFORMAT_VERSION" | tr '.' '_')"
readonly SWIFTFORMAT_BIN="$BIN_DIR/swiftformat_$SWIFTFORMAT_VERSION_STR"

function install() {
  local os="$(uname -s)"
  local arch="$(uname -m)"
  local download_file_name

  case "$os" in
    Darwin)
      # SwiftFormat releases provide a zip named exactly "swiftformat.zip" for macOS (universal)
      download_file_name="swiftformat.zip"
      ;;
    Linux)
      case "$arch" in
        x86_64|amd64)
          download_file_name="swiftformat_linux.zip"
          ;;
        aarch64|arm64)
          download_file_name="swiftformat_linux_aarch64.zip"
          ;;
        *)
          echo "Unsupported Linux architecture: $arch"
          exit 1
          ;;
      esac
      ;;
    *)
      echo "Unsupported OS: $os"
      exit 1
      ;;
  esac

  local download_url="https://github.com/nicklockwood/SwiftFormat/releases/download/${SWIFTFORMAT_VERSION}/${download_file_name}"

  mkdir -p "$BIN_DIR"
  local tmp_zip="$(mktemp)"
  local tmp_dir="$(mktemp -d)"
  cleanup() { rm -f "$tmp_zip"; rm -rf "$tmp_dir"; }
  trap cleanup EXIT

  echo "Downloading SwiftFormat ${SWIFTFORMAT_VERSION} → ${download_file_name}"
  curl -fsSL --progress-bar "$download_url" -o "$tmp_zip"

  echo "Extracting ${download_file_name}"
  unzip -q "$tmp_zip" -d "$tmp_dir"

  # Find the binary named 'swiftformat' in the extracted payload
  found_bin="$(find "$tmp_dir" -type f -name swiftformat -perm -u+x | head -n 1 || true)"
  if [ -z "${found_bin:-}" ]; then
    # Some archives may not keep +x bit; look for the file and chmod it.
    found_bin="$(find "$tmp_dir" -type f -name swiftformat | head -n 1 || true)"
    if [ -z "${found_bin:-}" ]; then
      echo "Failed to locate 'swiftformat' in ${download_file_name}"
      exit 1
    fi
    chmod +x "$found_bin"
  fi

  mv "$found_bin" "$SWIFTFORMAT_BIN"
  chmod +x "$SWIFTFORMAT_BIN"

  # On macOS, remove quarantine if present (harmless elsewhere)
  if command -v xattr >/dev/null 2>&1; then
    xattr -d com.apple.quarantine "$SWIFTFORMAT_BIN" 2>/dev/null || true
  fi
}

if [ ! -f "$SWIFTFORMAT_BIN" ]; then
  install >&2
fi

exec "$SWIFTFORMAT_BIN" "$@"
