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

readonly SWIFTLINT_VERSION="0.61.0"
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly BIN_DIR="$SCRIPT_DIR/.bin"
readonly SWIFTLINT_VERSION_STR="$(echo "$SWIFTLINT_VERSION" | tr '.' '_')"
readonly SWIFTLINT_BIN="$BIN_DIR/swiftlint_$SWIFTLINT_VERSION_STR"

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

  case "$os" in
    Darwin)
      # SwiftLint provides a universal macOS binary
      download_file_name="portable_swiftlint.zip"
      ;;
    Linux)
      case "$arch" in
        x86_64|amd64)
          download_file_name="swiftlint_linux_amd64.zip"
          ;;
        aarch64|arm64)
          download_file_name="swiftlint_linux_arm64.zip"
          ;;
        *)
          echo "Unsupported Linux architecture: $arch"
          exit 1
          ;;
      esac
      ;;
    *)
      echo "Unsupported OS: $os"
      exit 1
      ;;
  esac

  local download_url="https://github.com/realm/SwiftLint/releases/download/${SWIFTLINT_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 SwiftLint ${SWIFTLINT_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 'swiftlint' in the extracted payload
  found_bin="$(find "$tmp_dir" -type f -name swiftlint -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 swiftlint | head -n 1 || true)"
    if [ -z "${found_bin:-}" ]; then
      echo "Failed to locate 'swiftlint' in ${download_file_name}"
      exit 1
    fi
    chmod +x "$found_bin"
  fi

  mv "$found_bin" "$SWIFTLINT_BIN"
  chmod +x "$SWIFTLINT_BIN"

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

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

exec "$SWIFTLINT_BIN" "$@"
