spec:
  inputs:
    check-links-job-tags:
      description: tags to filter applicable runners for check-links build job
      type: array
      default: []
    tbc-check-job-tags:
      description: tags to filter applicable runners for tbc-checklinks build job
      type: array
      default: []
    tbc-check-image:
      description: image to use for tbc-check job
      type: string
      default: registry.gitlab.com/to-be-continuous/tools/tbc-check:latest
    gitlab-ci-lint-job-tags:
      description: tags to filter applicable runners for gitlab-ci-lint build job
      type: array
      default: []

---

.lint-scripts: &lint-scripts |
  set -e
  function log_info() {
    echo -e "[\e[1;94mINFO\e[0m] $*"
  }

  function log_warn() {
    echo -e "[\\e[1;93mWARN\\e[0m] $*"
  }

  function log_error() {
    echo -e "[\e[1;91mERROR\e[0m] $*" >&2
  }

  function install_ca_certs() {
    certs=$1
    if [[ -z "$certs" ]]
    then
      return
    fi

    # import in system
    if echo "$certs" >> /etc/ssl/certs/ca-certificates.crt
    then
      log_info "CA certificates imported in \\e[33;1m/etc/ssl/certs/ca-certificates.crt\\e[0m"
    fi
    if echo "$certs" >> /etc/ssl/cert.pem
    then
      log_info "CA certificates imported in \\e[33;1m/etc/ssl/cert.pem\\e[0m"
    fi
  }

  # validates an input GitLab CI YAML file
  function ci_lint() {
    rc=0
    for file in $(eval "ls -1 $GITLAB_CI_FILES")
    do
      log_info "Validating: $file..."
      cilint_req="{\"content\": $(jq --raw-input --slurp '.'  < "${file:-/dev/stdin}")}"
      cilint_resp=$(curl -s --header "Content-Type: application/json" --header "PRIVATE-TOKEN: $GITLAB_TOKEN" $CI_API_V4_URL/projects/$CI_PROJECT_ID/ci/lint --data "$cilint_req")
      if [ "$(echo "$cilint_resp" | jq -r '.valid')" == "true" ]
      then
        log_info " ... valid"
      else
        log_error " ... invalid"
        echo "$cilint_resp" | jq
        rc=1
      fi
    done
    exit $rc
  }

gitlab-ci-lint:
  image: registry.hub.docker.com/badouralix/curl-jq:latest
  stage: build
  before_script:
    - !reference [.lint-scripts]
    - install_ca_certs "${CUSTOM_CA_CERTS:-$DEFAULT_CA_CERTS}"
  script:
    - ci_lint
  rules:
    # enabled if $GITLAB_TOKEN and GITLAB_CI_FILES are set
    - if: '($GITLAB_TOKEN != null && $GITLAB_TOKEN != "") && $GITLAB_CI_FILES'
  tags: $[[ inputs.gitlab-ci-lint-job-tags ]]

check-links:
  image: 
    name: docker.io/lycheeverse/lychee:latest
    entrypoint: [""]
  stage: build
  script:
    - lychee --exclude www.gnu.org --exclude-path CHANGELOG.md --exclude-path SECURITY.md $LYCHEE_EXTRA_OPTS *.md
  tags: $[[ inputs.check-links-job-tags ]]

tbc-check:
  image:
    name: $[[ inputs.tbc-check-image ]]
    entrypoint: [""]
  stage: build
  script:
    - tbc-check .
  rules:
    - exists:
      - kicker.json
  tags: $[[ inputs.tbc-check-job-tags ]]