include:
  - template: Security/SAST.gitlab-ci.yml

sast:
  stage: build

nodejs-scan-sast:
  rules:
    - if: $SAST_DISABLED
      when: never
    - if: $CI_COMMIT_BRANCH != "develop"
      when: never
    - if: $CI_COMMIT_BRANCH &&
          $SAST_DEFAULT_ANALYZERS =~ /nodejs-scan/
      exists:
        - 'package.json'

eslint-sast:
  rules:
    - if: $SAST_DISABLED
      when: never
    - if: $CI_COMMIT_BRANCH != "develop"
      when: never
    - if: $CI_COMMIT_BRANCH &&
          $SAST_DEFAULT_ANALYZERS =~ /eslint/
      exists:
        - '**/*.html'
        - '**/*.js'
        - '**/*.jsx'
        - '**/*.ts'
        - '**/*.tsx'


stages:
  - build
  - deploy

dev-build-job:
  stage: build
  only:
    - develop
    - merge_requests
  image: docker:stable
  variables:
    POSTGRES_USER: postgres
    POSTGRES_PASSWORD: password
    POSTGRES_DB: demo_server
  services:
    - name: registry.lawsnote.com/postgres:13-pgroonga
      alias: postgres
    - name: redis:5-alpine
      alias: redis
  script:
    # 用 DATE-CI_COMMIT_SHA 當做 docker image 的 tag
    - DOCKER_IMAGE_TAG=$(date +%Y%m%d%H%M%S)-${CI_COMMIT_SHA:0:8}
    - DOCKER_BUILDKIT=1 docker build
      --ssh default="$SSH_PRIVATE_KEY"
      --build-arg CI_COMMIT_SHA="$CI_COMMIT_SHA"
      -t registry.lawsnote.com/professorx-dev:$DOCKER_IMAGE_TAG .
    # 使用 build 好的 image 測試
    - docker run 
      --rm
      -e DB_HOST=$POSTGRES_PORT_5432_TCP_ADDR
      -e DB_USER=postgres
      -e DB_PASSWORD=password
      -e DB_NAME=demo_server
      -e REDIS_HOST=$REDIS_PORT_6379_TCP_ADDR
      -e SMS_VENDER=empty
      -e NODE_ENV=test
      registry.lawsnote.com/professorx-dev:$DOCKER_IMAGE_TAG yarn test-with-db
    # push docker image
    - docker push registry.lawsnote.com/professorx-dev:$DOCKER_IMAGE_TAG
    # tag latest
    - docker tag registry.lawsnote.com/professorx-dev:$DOCKER_IMAGE_TAG registry.lawsnote.com/professorx-dev:latest
    - docker push registry.lawsnote.com/professorx-dev:latest
    # delete local image
    - docker rmi registry.lawsnote.com/professorx-dev:latest
    # 執行 Galactus 來刪除不必要的 image，只保留 10 個舊版
    - docker run --rm --env TARGET_IMAGE=professorx-dev --env KEEP_COUNT=10 --env FORCE=1 registry.lawsnote.com/galactus:latest
  tags:
    - docker

dev-deploy-job:
  stage: deploy
  only:
    - develop
  script:
    - docker pull registry.lawsnote.com/professorx-dev:latest
    - if [ "$(docker inspect -f '{{.State.Running}}' professorx-dev 2> /dev/null)" == "true" ]; then docker rm -f -v professorx-dev; fi
    - docker run --detach --restart always --log-driver=json-file --log-opt max-size=16m --log-opt max-file=2 --publish 30041:10230 --name professorx-dev --env-file "$DEV_SERVICE_ENV" registry.lawsnote.com/professorx-dev:latest
  tags:
    - office
