image: ubuntu:focal
variables:
  DEBIAN_FRONTEND: noninteractive
  GIT_SUBMODULE_STRATEGY: recursive
  CHECKOUT_BRANCH: main
stages:
  - build
  - deploy


site:
  stage: build
  rules:
    - if: $UPSTREAM_BRANCH
      variables:
        CHECKOUT_BRANCH: $UPSTREAM_BRANCH
    - when: on_success
  before_script:
    - apt-get update && apt-get install -y --no-install-recommends python3-pip python3 make git wget software-properties-common
    - wget -O pandoc.deb https://github.com/jgm/pandoc/releases/download/2.18/pandoc-2.18-1-amd64.deb && dpkg -i pandoc.deb && rm --interactive=never pandoc.deb
    - pip3 install -r requirements.txt
    - "echo \"CHECKOUT_BRANCH: $CHECKOUT_BRANCH UPSTREAM_BRANCH: $UPSTREAM_BRANCH\""
    - git clone https://gitlab.gwdg.de/GAUMI-fginfo/fg-website-data.git content --branch $CHECKOUT_BRANCH
  script:
    - make publish
  artifacts:
    paths:
      - "./output/"


docs:
  stage: build
  before_script:
    - apt-get update && apt-get install -y --no-install-recommends python3-pip python3 make git wget software-properties-common
    - wget -O pandoc.deb https://github.com/jgm/pandoc/releases/download/2.18/pandoc-2.18-1-amd64.deb && dpkg -i pandoc.deb && rm --interactive=never pandoc.deb
    - pip3 install -r requirements.txt
  script:
    - make docs
  artifacts:
    paths:
      - "./docs-output/"
  rules:
    - when: on_success

pages:
  stage: deploy
  needs: [ "site", "docs" ]
  script:
    - mkdir -p ./public
    - cp -v ./index.html ./public/
    - mv -v ./output/ ./public/
    - mv -v ./docs-output/ ./public/
  artifacts:
    paths:
      - "./public/"
  rules:
    - when: on_success
  environment:
    name: staging


deploy:
  stage: deploy
  needs: [ "site" ]
  before_script:
    - "echo \"CHECKOUT_BRANCH: $CHECKOUT_BRANCH UPSTREAM_BRANCH: $UPSTREAM_BRANCH\""
    # see https://filipsjanis.com/articles/scp-upload-files-gitlab-ci.html
    # the following script is taken from https://docs.gitlab.com/ee/ci/ssh_keys/README.html
    - 'DEBIAN_FRONTEND=noninteractive apt-get update -y'
    - 'DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends openssh-client'
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
  script:
    - scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -r ./output/** $USERNAME@$HOST:/home/gitlab/public/
  rules:
    - if: $CI_COMMIT_REF_NAME != $CI_DEFAULT_BRANCH
      when: never
    - if: $UPSTREAM_BRANCH && $UPSTREAM_BRANCH != "main"
      when: never
    - when: on_success
  environment:
    name: production
  #when: manual