#!/usr/bin/env bash

remote="$1"
url="$2"

zero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')

check_lint () {
  # Run lint check
  cargo fmt --all --check
  if [ $? -ne 0 ]; then
    echo >&2 "Please run 'cargo fmt' and commit the formatting changes."
    exit 1
  fi
}

check_code_warnings () {
  # Run clippy to check for warnings
  cargo clippy --all-features --all-targets --tests --benches -- -Dclippy::all
  if [ $? -ne 0 ]; then
    echo >&2 "Please run 'cargo clippy' and fix the warnings."
    exit 1
  fi
}

while read local_ref local_oid remote_ref remote_oid
do
  if test "$local_oid" = "$zero"; then
    # Handle delete
    :
  else
    if test "$remote_oid" = "$zero"; then
      # No existing commits yet on the new branch (no remote yet).
      # Examine all local commits.
      range="$local_oid"
    else
      # Examine new commits from local that is missing from remote branch.
      # Update to existing branch.
      range="$remote_oid..$local_oid"
    fi

    # Check for WIP commit
    commit=$(git rev-list -n 1 --grep '^--wip--' "$range")
    if test -n "$commit"
    then
      echo >&2 "Found WIP commit in $local_ref, not pushing."
      exit 1
    fi

    check_lint

    check_code_warnings
  fi
done

exit 0
