.pre-deploy-uber-space-setup: &pre-deploy-uber-space-setup
  - apk add rsync openssh-client
  - eval $(ssh-agent -s)
  - echo "$CI_DEPLOYMENT_PRIVATE_KEY" | tr -d '\r' | ssh-add -
  - mkdir -p ~/.ssh
  - chmod 700 ~/.ssh
  - echo "$UBERSPACE_KNOWN_HOST" >> ~/.ssh/known_hosts

workflow:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
    - if: '$CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS'
      when: never
    - if: '$CI_COMMIT_BRANCH'

stages:
  - build
  - upload

build:
  stage: build
  image: node:current-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="/preview/fit-connect/$CI_COMMIT_REF_SLUG/"
    - yarn build
  artifacts:
    expose_as: 'Built Documentation'
    paths:
      - build/
    expire_in: 30 days
  rules:
    - when: always

upload:review:
  stage: upload
  image: alpine:latest
  environment:
    name: review/$CI_COMMIT_REF_NAME
    on_stop: stop:review
    auto_stop_in: 2 week
    url: https://docs.fitko.de/preview/fit-connect/$CI_COMMIT_REF_SLUG
  needs:
    - build
  rules:
    - if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
  before_script:
    - *pre-deploy-uber-space-setup
  script:
    - rsync -rLvz --delete --checksum -e "ssh -o CheckHostIP=no" --ipv4 --progress ./build/. fitko@dorado.uberspace.de:html/preview/fit-connect/$CI_COMMIT_REF_SLUG

upload:production:
  stage: upload
  image: alpine:latest
  environment:
    name: production
    url: https://docs.fitko.de/fit-connect/
  needs:
    - build
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
  before_script:
    - *pre-deploy-uber-space-setup
  script:
    - rsync -rLvz --delete --checksum -e "ssh -o CheckHostIP=no" --ipv4 --progress ./build/. fitko@dorado.uberspace.de:html/fit-connect

stop:review:
  stage: .post
  image: alpine:latest
  environment:
    name: review/$CI_COMMIT_REF_NAME
    action: stop
  needs:
    - upload:review
  rules:
    - if: $CI_MERGE_REQUEST_ID
      when: manual
  before_script:
    - *pre-deploy-uber-space-setup
  script:
    - ssh fitko@dorado.uberspace.de "rm -rf html/preview/fit-connect/$CI_COMMIT_REF_SLUG"
