#!/usr/bin/env sh
set -eu

base_url="${INTEL_RELEASE_BASE_URL:-https://releases.i10e.app}"
version="${INTEL_VERSION:-latest}"
install_dir="${INTEL_INSTALL_DIR:-$HOME/.local/bin}"

need() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "intel installer requires $1" >&2
    exit 1
  fi
}

need curl
need tar

case "$(uname -s)" in
  Darwin) os="darwin" ;;
  Linux) os="linux" ;;
  *)
    echo "unsupported OS: $(uname -s)" >&2
    exit 1
    ;;
esac

case "$(uname -m)" in
  x86_64 | amd64) arch="amd64" ;;
  arm64 | aarch64) arch="arm64" ;;
  *)
    echo "unsupported architecture: $(uname -m)" >&2
    exit 1
    ;;
esac

base_url="${base_url%/}"
if [ "$version" = "latest" ]; then
  version="$(curl -fsSL "$base_url/intel/latest.txt" | tr -d '[:space:]')"
fi

if [ -z "$version" ]; then
  echo "could not resolve intel version" >&2
  exit 1
fi

archive="intel_${version}_${os}_${arch}.tar.gz"
version_url="$base_url/intel/$version"
tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT INT TERM

curl -fsSL "$version_url/$archive" -o "$tmpdir/$archive"
curl -fsSL "$version_url/intel_${version}_checksums.txt" -o "$tmpdir/checksums.txt"

if command -v sha256sum >/dev/null 2>&1; then
  (cd "$tmpdir" && grep "  $archive\$" checksums.txt | sha256sum -c -)
elif command -v shasum >/dev/null 2>&1; then
  expected="$(grep "  $archive\$" "$tmpdir/checksums.txt" | awk '{print $1}')"
  actual="$(shasum -a 256 "$tmpdir/$archive" | awk '{print $1}')"
  if [ "$expected" != "$actual" ]; then
    echo "checksum mismatch for $archive" >&2
    exit 1
  fi
else
  echo "intel installer requires sha256sum or shasum" >&2
  exit 1
fi

tar -xzf "$tmpdir/$archive" -C "$tmpdir"
mkdir -p "$install_dir"
install "$tmpdir/intel" "$install_dir/intel"

echo "intel $version installed to $install_dir/intel"
case ":$PATH:" in
  *":$install_dir:"*) ;;
  *) echo "add $install_dir to PATH to run intel from any shell" ;;
esac
