---
include:
  - remote: https://jobs.just-ci.dev/v6.19.1/project-automation/telemetry.yml

pages:
  extends: .telemetry
  stage: build
  image:
    name: docker.io/alpine/git:latest
    entrypoint: [""]
  variables:
    GIT_STRATEGY: clone
  script:
    - |
      if [ "$(git rev-parse --is-shallow-repository)" != "false" ]; then
        echo "[*] Repository is shallow. Unshallowing."
        git fetch --unshallow -q
      fi
    - apk add -q grep tree
    - GIT_TAGS=$(git tag --format "%(refname:strip=1)") # Produces list with 'tags/' prefix
    - GIT_BRANCHES=$(git branch -r --format "%(refname:strip=3)")
    - mkdir -p /tmp/public
    - |
      for GIT_REF in ${GIT_TAGS} ${GIT_BRANCHES}; do
        printf "[*] Processing ${GIT_REF}..."
        git checkout ${GIT_REF} -q

        FILES=$(grep -rl "\- remote: "https://jobs.just-ci.dev/v6.19.1/ . --exclude-dir=tests --exclude=.gitlab-ci.yml --exclude=pages-templates.yaml)
        printf "$(echo ${FILES} | wc -w) file(s)..."

        GIT_REF_NAME=${GIT_REF#tags/}
        echo ${FILES} | xargs sed -i "s|- remote: https://jobs.just-ci.dev/v6.19.1/\"|- remote: \"${CI_PAGES_URL}/${GIT_REF_NAME}/|g"
        echo ${FILES} | xargs sed -i "s|- remote: https://jobs.just-ci.dev/v6.19.1/|- remote: ${CI_PAGES_URL}/${GIT_REF_NAME}/|g"
        cp -r . /tmp/public/${GIT_REF_NAME}
        rm -rf /tmp/public/${GIT_REF_NAME}/.git

        git reset --hard -q
        echo "done."
      done
    - echo "[*] Publishing $(echo $GIT_TAGS | wc -w) tags and $(echo
      $GIT_BRANCHES | wc -w) branches to ${CI_PAGES_URL}..."
    - mv /tmp/public ${CI_PROJECT_DIR}/public
    - find ${CI_PROJECT_DIR}/public -type f ! -name "*.yaml" ! -name "*.yml"
      -delete
    - find ${CI_PROJECT_DIR}/public -type d -empty -delete
    - cd ${CI_PROJECT_DIR}/public
    - tree -H '.' --noreport --dirsfirst -T "${PAGES_TEMPLATES_NAME:-Templates}"
      --charset utf-8 -o index.html .
  needs: []
  artifacts:
    paths:
      - public
