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

check_complete_tree() {
  local empty_tree
  empty_tree="$(git hash-object -t tree /dev/null)"
  git diff --check "$empty_tree" HEAD
}

check_range() {
  local base_sha="$1"
  local separator="$2"

  if [[ -z "$base_sha" ]]; then
    check_complete_tree
    return
  fi

  if [[ ! "$base_sha" =~ ^[0-9a-fA-F]{40,64}$ ]]; then
    printf 'The event value is not a valid commit SHA.\n' >&2
    exit 64
  fi

  if [[ "$base_sha" =~ ^0+$ ]]; then
    check_complete_tree
    return
  fi

  git diff --check "${base_sha}${separator}HEAD"
}

case "${CI_EVENT_NAME:-}" in
  pull_request)
    check_range "${CI_PR_BASE_SHA:-}" '...'
    ;;
  push)
    check_range "${CI_PUSH_BEFORE_SHA:-}" '..'
    ;;
  *)
    printf 'CI_EVENT_NAME must be pull_request or push.\n' >&2
    exit 64
    ;;
esac
