.ssh-setup: &ssh-setup
  - eval $(ssh-agent -s)
  - echo "$CI_DEPLOYMENT_PRIVATE_KEY" | tr -d '\r' | ssh-add -
  - echo "$UBERSPACE_KNOWN_HOST" >> ~/.ssh/known_hosts

include:
  - project: 'fit-connect/pipeline'
    ref: main
    file: 'workflows/no-duplicate-pipelines.gitlab-ci.yml'

stages:
  - build
  - upload
  - validate

build:
  stage: build
  image: node:lts-alpine
  variables:
    GIT_BRANCH: $CI_COMMIT_REF_NAME
  before_script:
    - apk add git
    - yarn
  script:
    - export DOCUSAURUS_BASE_URL="/fit-connect/" && [[ "$CI_COMMIT_REF_NAME" != "main" ]] && export DOCUSAURUS_BASE_URL="/fit-connect/$CI_COMMIT_REF_SLUG/"
    - yarn build
  artifacts:
    expose_as: 'Built Documentation'
    paths:
      - build/
    expire_in: 30 days
  rules:
    - when: always

upload:preview:
  stage: upload
  image: ${CI_REGISTRY}/fit-connect/baseimage:latest
  environment:
    name: preview/$CI_COMMIT_REF_NAME
    on_stop: stop:preview
    auto_stop_in: 2 week
    url: https://preview.docs.fitko.dev/fit-connect/$CI_COMMIT_REF_SLUG/
  needs:
    - build
  rules:
    - if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
  before_script:
    - *ssh-setup
  script:
    - ssh -o CheckHostIP=no fitko@dorado.uberspace.de mkdir -p preview.docs.fitko.dev/fit-connect
    - rsync -rLvz --delete --checksum -e "ssh -o CheckHostIP=no" --ipv4 --progress ./build/. fitko@dorado.uberspace.de:preview.docs.fitko.dev/fit-connect/$CI_COMMIT_REF_SLUG

upload:production:
  stage: upload
  image: ${CI_REGISTRY}/fit-connect/baseimage:latest
  environment:
    name: production
    url: https://docs.fitko.de/fit-connect/
  needs:
    - build
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
  before_script:
    - *ssh-setup
  script:
    - ssh -o CheckHostIP=no fitko@dorado.uberspace.de mkdir -p docs.fitko.de/fit-connect
    - rsync -rLvz --delete --checksum -e "ssh -o CheckHostIP=no" --ipv4 --progress ./build/. fitko@dorado.uberspace.de:docs.fitko.de/fit-connect

stop:preview:
  stage: .post
  image: ${CI_REGISTRY}/fit-connect/baseimage:latest
  environment:
    name: preview/$CI_COMMIT_REF_NAME
    action: stop
  needs:
    - upload:preview
  rules:
    - if: $CI_MERGE_REQUEST_ID
      when: manual
  before_script:
    - *ssh-setup
  script:
    - ssh fitko@dorado.uberspace.de "rm -rf preview.docs.fitko.dev/fit-connect/$CI_COMMIT_REF_SLUG"

link-check:
  stage: validate
  rules:
    - if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH # live docs
      variables:
        CRAWLER_URL: https://docs.fitko.de/fit-connect/docs
        CRAWLER_DOMAIN: docs.fitko.de/fit-connect/docs
    - if: $CI_COMMIT_REF_NAME != $CI_DEFAULT_BRANCH # preview docs
      variables:
        CRAWLER_URL: https://preview.docs.fitko.dev/fit-connect/$CI_COMMIT_REF_SLUG/
        CRAWLER_DOMAIN: preview.docs.fitko.dev/fit-connect/$CI_COMMIT_REF_SLUG/
  trigger:
    strategy: depend
    project: fit-connect/schema-link-checker
    branch: main
