image: quantumtinkerer/research

stages:
  - build
  - deploy

build lectures:
  stage: build
  before_script:
    - pip install -U mkdocs mkdocs-material python-markdown-math notedown
  script:
    - python execute.py
    - mkdocs build
  artifacts:
    paths:
      - site
    expire_in: 1 week

.prepare_deploy: &prepare_deploy
  stage: deploy
  only:
    - branches@solidstate/lectures
  before_script:
    ## Install ssh-agent if not already installed, it is required by Docker.
    ## (change apt-get to yum if you use an RPM-based image)
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'

    ## Run ssh-agent (inside the build environment)
    - eval $(ssh-agent -s)

    ## Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
    ## We're using tr to fix line endings which makes ed25519 keys work
    ## without extra base64 encoding.
    ## https://gitlab.com/gitlab-examples/ssh-private-key/issues/1#note_48526556
    - echo "$WEBSITE_UPLOAD_KEY" | tr -d '\r' | ssh-add - > /dev/null

    ## Create the SSH directory and give it the right permissions
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan tnw-tn1.tudelft.net >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
  script:
    - "rsync -rv site/* solidstate@tnw-tn1.tudelft.net:$DEPLOY_PATH"

deploy delft version:
  <<: *prepare_deploy
  only:
    - local@solidstate/lectures
  variables:
    DEPLOY_PATH: ""
  environment:
    name: $CI_COMMIT_REF_NAME
    url: "https://solidstate.quantumtinkerer.tudelft.nl/"

deploy test version:
  <<: *prepare_deploy
  except:
    - local@solidstate/lectures
  variables:
    DEPLOY_PATH: "test_builds/$CI_COMMIT_REF_NAME"
  environment:
    name: $CI_COMMIT_REF_NAME
    url: "https://solidstate.quantumtinkerer.tudelft.nl/test_builds/$CI_COMMIT_REF_NAME"
    on_stop: undeploy test version

undeploy test version:
  <<: *prepare_deploy
  except:
    - local@solidstate/lectures
  when: manual
  variables:
    DEPLOY_PATH: "test_builds/$CI_COMMIT_REF_NAME"
  script:
    - mkdir empty/
    - "rsync -rlv --delete empty/ solidstate@tnw-tn1.tudelft.net:$DEPLOY_PATH"
  environment:
    name: $CI_COMMIT_REF_NAME
    action: stop

merge into local:
  stage: deploy
  only:
    - master@solidstate/lectures
  script:
    - git checkout master; git reset --hard origin/master
    - git checkout local; git reset --hard origin/local
    - git diff-index --quiet master || git -c "user.name=$GITLAB_USER_NAME" -c "user.email=$GITLAB_USER_EMAIL" merge master
    - "git push https://$GITLAB_PUSH_KEY@gitlab.kwant-project.org/solidstate/lectures.git local"
