#!/bin/bash

set -e -o pipefail

# Download actionlint if not already present
ACTIONLINT_VERSION="1.7.7"
ACTIONLINT_DIR="/tmp/actionlint-${ACTIONLINT_VERSION}"
ACTIONLINT_BIN="${ACTIONLINT_DIR}/actionlint"

if [ ! -f "${ACTIONLINT_BIN}" ]; then
    echo "Downloading actionlint v${ACTIONLINT_VERSION}..."
    mkdir -p "${ACTIONLINT_DIR}"

    # Detect OS and architecture
    case "$OSTYPE" in
        linux-*) os=linux; ext=tar.gz ;;
        darwin*) os=darwin; ext=tar.gz ;;
        *) echo "OS '${OSTYPE}' is not supported" >&2; exit 1 ;;
    esac

    machine="$(uname -m)"
    case "$machine" in
        x86_64) arch=amd64 ;;
        aarch64|arm64) arch=arm64 ;;
        *) echo "Could not determine arch from machine '${machine}'" >&2; exit 1 ;;
    esac

    # Download actionlint
    url="https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_${os}_${arch}.${ext}"
    echo "Downloading from: ${url}"
    curl -L "${url}" | tar xz -C "${ACTIONLINT_DIR}" actionlint
else
    echo "Using cached actionlint from ${ACTIONLINT_BIN}"
fi

# Create actionlint config if it doesn't exist
ACTIONLINT_CONFIG=".github/actionlint.yaml"
if [ ! -f "${ACTIONLINT_CONFIG}" ]; then
    echo "Creating actionlint config at ${ACTIONLINT_CONFIG}"
    cat > "${ACTIONLINT_CONFIG}" << 'EOF'
# Configuration for actionlint
# Auto-generated by .github/scripts/actionlint.sh
self-hosted-runner:
  labels:
    - ubuntu-amd64-8core
    - ubuntu-amd64-16core
    - ubuntu-amd64-32core
    - Reth
EOF
fi

# Run actionlint with proper configuration
echo "Running actionlint..."
SHELLCHECK_OPTS="-S error" "${ACTIONLINT_BIN}" -color "$@"
