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

tag="${EVERY_CHANNEL_OP_DEPLOYER_TAG:-op-deployer/v0.6.0-rc.3}"
out="${EVERY_CHANNEL_OP_DEPLOYER_OUT:-./op-deployer}"

log() {
  printf '[op-deployer] %s\n' "$*" >&2
}

detect_platform() {
  local os arch
  case "$(uname -s)" in
    Darwin) os="darwin" ;;
    Linux) os="linux" ;;
    *) echo "unsupported-os" ; return 1 ;;
  esac
  case "$(uname -m)" in
    aarch64|arm64) arch="arm64" ;;
    x86_64|amd64) arch="amd64" ;;
    *) echo "unsupported-arch" ; return 1 ;;
  esac
  printf '%s-%s\n' "$os" "$arch"
}

platform="$(detect_platform)"
if [[ "$platform" == unsupported-* ]]; then
  log "unsupported platform: $(uname -s)/$(uname -m)"
  exit 2
fi

version="${tag#op-deployer/v}"
archive="op-deployer-${version}-${platform}.tar.gz"
url="https://github.com/ethereum-optimism/optimism/releases/download/${tag}/${archive}"
tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT

log "downloading ${tag} for ${platform}"
curl -fsSL "$url" -o "${tmpdir}/archive.tar.gz"
tar -xzf "${tmpdir}/archive.tar.gz" -C "$tmpdir"

candidate="$(find "$tmpdir" -type f -name 'op-deployer*' -perm -u+x | head -n 1)"
if [[ -z "$candidate" ]]; then
  log "failed to locate extracted op-deployer binary"
  exit 1
fi

install -m 0755 "$candidate" "$out"
log "wrote ${out}"
