.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

stages:
  - build
  - upload

build:
  stage: build
  image: $CI_REGISTRY/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

upload:review:
  stage: upload
  image: $CI_REGISTRY/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
  rules:
    - if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
  before_script:
    - *pre-deploy-uber-space-setup
  script:
    - rsync -rLvz --size-only --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: $CI_REGISTRY/alpine:latest
  environment:
    name: production
    url: https://docs.fitko.de/fit-connect/
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
  before_script:
    - *pre-deploy-uber-space-setup
  script:
    - rsync -rLvz --size-only --checksum -e "ssh -o CheckHostIP=no" --ipv4 --progress ./build/. fitko@dorado.uberspace.de:html/fit-connect

stop:review:
  stage: .post
  image: $CI_REGISTRY/alpine:latest
  environment:
    name: review/$CI_COMMIT_REF_NAME
    action: stop
  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"
