before_script:
  - 'which ssh-agent || ( yum install -qq openssh-client )'
  - eval $(ssh-agent -s)
  - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
  - mkdir -p ~/.ssh
  - chmod 700 ~/.ssh
  - ssh-keyscan -t rsa 192.168.1.201 >> ~/.ssh/known_hosts
  - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
  - whoami
  - unset SSH_ASKPASS

variables:
  QUALITY_GATE: "OK"

stages:
  - checkout
  - compile
  - sonnar_scanner
  - check_quality_gate
  - dokcer_build
  - send_email

checkout:
  stage: checkout
  only:
    - master
    - merge_request
  script:
    - ls # test command
    - cd /root/GitlabRunner/repo/
    - ls
    - rm -rf ./spring-ci-advanced
    - git config --global user.name 'truongbb96'
    - git config --global user.email 'truongbb@itsol.vn'
    - git clone https://truongbb96:hoanghuynh0801@git.myitsol.com/truongbb96/spring-ci-advanced.git
    - cd ./spring-ci-advanced

compile:
  stage: compile
  only:
    - master
    - merge_request
  script:
    - cd /root/GitlabRunner/repo/spring-ci-advanced
    - ls
    - chmod +x ./build-test.sh
    - ./build-test.sh compile

sonnar_scanner:
  stage: sonnar_scanner
  only:
    - master
    - merge_requests
  script:
    - cd /root/GitlabRunner/repo/spring-ci-advanced
    - ls
    - chmod +x ./build-test.sh
    - ./build-test.sh sonar-scan

check_quality_gate:
  stage: check_quality_gate
  only:
    - master
    - merge_requests
  script:
    - cd /root/GitlabRunner/repo/spring-ci-advanced
    - ls
    - chmod +x ./build-test.sh
    - export QUALITY_GATE=$(./build-test.sh quality-gate)
    - echo $QUALITY_GATE
    - echo "Sonar statistic result at --> http://192.168.1.210:9000/dashboard?id=spring-ci-advanced"
    # force pipeline exit and fail job if QUALITY GATE is FAIL
    - sh ./stop_job.sh

dokcer_build:
  stage: dokcer_build
  only:
    - master
  #    - merge_requests
  script:
    - cd /root/GitlabRunner/repo/spring-ci-advanced
    - ls
    - chmod +x ./build-test.sh
    - ./build-test.sh docker-build
    - ./build-test.sh docker-up
    - ./build-test.sh docker-push

send_email:
  stage: send_email
  only:
    - master
    - merge_requests
  script:
    - curl --request POST
      --url https://api.sendgrid.com/v3/mail/send
      --header 'Authorization:Bearer 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'
      --header 'Content-Type:application/json'
      --data '{"personalizations":[{"to":[{"email":"truongbb96@gmail.com"}]}],"from":{"email":"truongbb@itsol.vn"},"subject":"CI pipeline result","content":[{"type":"text/plain","value":"CI pipeline done!"}]}'