#!/bin/bash
set -e

repo="k1LoW/gh-grep"
tag=v0.11.0

extensionPath="$(dirname "$0")"
arch="$(uname -m)"

exe=""

if uname -a | grep Msys > /dev/null; then
  if [ $arch = "x86_64" ]; then
    exe="gh-grep_${tag}_windows_amd64.exe"
  fi
elif uname -a | grep Darwin > /dev/null; then
  if [ $arch = "x86_64" ]; then
    exe="gh-grep_${tag}_darwin_amd64"
  elif [ $arch = "arm64" ]; then
    exe="gh-grep_${tag}_darwin_arm64"
  fi
elif uname -a | grep Linux > /dev/null; then
  if [ $arch = "x86_64" ]; then
    exe="gh-grep_${tag}_linux_amd64"
  fi
fi

if [ "${exe}" == "" ]; then
  if [ "$(which go)" = "" ]; then
    echo "go must be installed to use this gh extension on this platform"
    exit 1
  fi

  exe="cmd.out"

  cd "${extensionPath}" > /dev/null
  go build -o "${exe}"
  cd - > /dev/null
else
  if [[ ! -x "${extensionPath}/bin/${exe}" ]]; then
    mkdir -p "${extensionPath}/bin"
    rm -f "${extensionPath}/bin/*"
    gh release -R"${repo}" download "${tag}" -p "${exe}" --dir="${extensionPath}/bin"
    chmod +x "${extensionPath}/bin/${exe}"
  fi
fi

exec "${extensionPath}/bin/${exe}" "$@"
