image: node:16-alpine
stages:
  - setup
  - test
  - docker
  - deploy

install-dependencies:
  stage: setup
  interruptible: true
  only:
    - main
    - merge_requests
  cache:
    key:
      files:
        - yarn.lock
    paths:
      - node_modules
      - .yarn
  script:
    - yarn install --pure-lockfile --cache-folder .yarn
  artifacts:
    paths:
      - node_modules

.distributed:
  interruptible: true
  only:
    - main
    - merge_requests
  needs:
    - install-dependencies
  artifacts:
    paths:
      - node_modules/.cache/nx

build:
  stage: test
  extends: .distributed
  script:
    - yarn nx affected --base=HEAD~1 --target=build --parallel --max-parallel=3

test:
  stage: test
  extends: .distributed
  script:
    - yarn nx affected --base=HEAD~1 --target=test --parallel --max-parallel=2

docker:
  image: docker:stable
  stage: docker
  tags:
    - docker
  only:
    - main
    - develop
  script:
    - docker build --progress plain -f ./apps/frontend/Dockerfile . -t $CI_PROJECT_NAME:latest
  after_script:
    - docker login datastropheregistry.azurecr.io -u $REGISTRY_USERNAME -p $REGISTRY_PASSWORD
    - if [[ ! -z $CI_COMMIT_BRANCH+x ]]; then DOCKER_TAG=$CI_COMMIT_BRANCH; else DOCKER_TAG=$CI_MERGE_REQUEST_TARGET_BRANCH_NAME; fi
    - docker tag $CI_PROJECT_NAME datastropheregistry.azurecr.io/$CI_PROJECT_NAME:$DOCKER_TAG
    - docker push datastropheregistry.azurecr.io/$CI_PROJECT_NAME:$DOCKER_TAG
  dependencies:
    - build

deploy:
  stage: deploy
  only:
    - main
    - develop
  script:
    - apk add --update --no-cache openssh-client >/dev/null
    - mkdir ~/.ssh/
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa
    - chmod 600 ~/.ssh/id_rsa
    - ssh-add ~/.ssh/id_rsa
    - echo "$SSH_KNOWN_HOSTS" >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
    - ssh -fN -L 1234:science-vs260.science.uu.nl:22 sivan@up.science.uu.nl
    # Copy kubernetes files over
    - scp -r -o StrictHostKeyChecking=no -P 1234 -i ~/.ssh/id_rsa deployments/* root@localhost:/root/kubernetes/$CI_PROJECT_NAME
    # Deploy all yml files
    - ssh -p 1234 -i ~/.ssh/id_rsa root@localhost "for i in kubernetes/$CI_PROJECT_NAME/*.yml; do kubectl apply -f \$i; done"
    # Perform rolling update for deployment
    - ssh -p 1234 -i ~/.ssh/id_rsa root@localhost "kubectl rollout restart -f kubernetes/$CI_PROJECT_NAME/deployment.yml"
  dependencies: []