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

SERVICE="${1:-}"
CHECK="${2:-}"

if [ -z "${SERVICE}" ] || [ -z "${CHECK}" ]; then
  echo "usage: $0 <service-key> <lint|tests>" >&2
  exit 2
fi

COMMIT_MESSAGE="${WOODPECKER_COMMIT_MESSAGE:-${CI_COMMIT_MESSAGE:-${GIT_COMMIT_MESSAGE:-}}}"
if [ -z "${COMMIT_MESSAGE}" ]; then
  exit 1
fi

contains_token() {
  token="$1"
  printf '%s' "${COMMIT_MESSAGE}" | grep -Fq -- "${token}"
}

emit_skip() {
  token="$1"
  scope="$2"
  printf 'bypass enabled by token %s (%s scope)' "${token}" "${scope}"
  exit 0
}

if contains_token "[skip-checks]"; then
  emit_skip "[skip-checks]" "all-modules"
fi
if contains_token "[skip-checks:all]"; then
  emit_skip "[skip-checks:all]" "all-modules"
fi
if contains_token "[skip-checks:${SERVICE}]"; then
  emit_skip "[skip-checks:${SERVICE}]" "service"
fi

case "${CHECK}" in
  lint)
    if contains_token "[skip-lint]"; then
      emit_skip "[skip-lint]" "all-modules"
    fi
    if contains_token "[skip-lint:all]"; then
      emit_skip "[skip-lint:all]" "all-modules"
    fi
    if contains_token "[skip-lint:${SERVICE}]"; then
      emit_skip "[skip-lint:${SERVICE}]" "service"
    fi
    ;;
  tests)
    if contains_token "[skip-tests]"; then
      emit_skip "[skip-tests]" "all-modules"
    fi
    if contains_token "[skip-tests:all]"; then
      emit_skip "[skip-tests:all]" "all-modules"
    fi
    if contains_token "[skip-tests:${SERVICE}]"; then
      emit_skip "[skip-tests:${SERVICE}]" "service"
    fi
    if contains_token "[skip-autotests]"; then
      emit_skip "[skip-autotests]" "all-modules"
    fi
    if contains_token "[skip-autotests:all]"; then
      emit_skip "[skip-autotests:all]" "all-modules"
    fi
    if contains_token "[skip-autotests:${SERVICE}]"; then
      emit_skip "[skip-autotests:${SERVICE}]" "service"
    fi
    ;;
  *)
    echo "unsupported check: ${CHECK}" >&2
    exit 2
    ;;
esac

exit 1
