#!/usr/bin/env bash

usage() {
  echo -e "Usage:\n\tcheck-header-guard.sh <headerfile>"
}

if [ $# -eq 0 ]; then
  usage >&2
  exit 2
fi

_result=0
for _file in "$@"; do
  if [ ! -f $_file ]; then
    echo >&2 "check-header-guard.sh: error: '$_file' does not exist"
    exit 2
  fi

  _guard=$(awk '/^#ifndef/ { print $2; exit }' < $_file)

  _path_from_src=$(realpath -m --relative-to=src/include $_file)
  _path_from_test=$(realpath -m --relative-to=tests $_file)

  if ! [[ ${_path_from_src} =~ "../" ]]; then
    _expected=$(echo ${_path_from_src} | tr '[:lower:]' '[:upper:]' | tr '/.' '_')
  elif ! [[ ${_path_from_test} =~ "../" ]]; then
    _expected=$(echo ${_path_from_test} | tr '[:lower:]' '[:upper:]' | tr '/.' '_')
    _expected=$(echo TANGO_TEST_${_expected})
  else
    echo >&2 "check-header-guard.sh: error: '$_file' is not realtive to 'src/include/' or 'tests/'"
    exit 2
  fi

  if [ -z ${_guard} ] || ! grep "#define ${_guard}" $_file &> /dev/null; then
    echo >&2 "No header guard found in '$_file', expected '$_expected'"
    _result=1
    continue
  fi

  if [[ $_guard != $_expected ]]; then
    sed -i "s/${_guard}/${_expected}/" $_file
  fi
done

exit $_result
