variables:
  K8S_API_URL: https://172.20.100.2:6443

stages:
  - build
  - test
  - cleanup
  - push
  - deploy

build:
  stage: build
  script:
    - docker build -t $CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME:$CI_COMMIT_REF_SLUG.$CI_PIPELINE_ID .

test:
  stage: test
  image:
    name: docker/compose:1.27.4
    entrypoint: [""]
  script:
    - docker-compose 
        -p "$CI_PROJECT_NAME"_"$CI_PIPELINE_ID"
      up
        --abort-on-container-exit
        --exit-code-from app
        --quiet-pull

cleanup:
  stage: cleanup
  image:
    name: docker/compose:1.27.4
    entrypoint: [""]
  script:
    - docker-compose -p "$CI_PROJECT_NAME"_"$CI_PIPELINE_ID" down
  when: always

push:
  stage: push
  before_script:
    - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY
  script:
    - docker push $CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME:$CI_COMMIT_REF_SLUG.$CI_PIPELINE_ID
  only:
    - master

deploy:
  stage: deploy
  image: centosadmin/kubernetes-helm:3.3.4
  environment:
    name: production
  resource_group: deploy_production
  script:
    - kubectl config set-cluster k8s --insecure-skip-tls-verify=true --server=$K8S_API_URL
    - kubectl config set-credentials ci --token=$K8S_CI_TOKEN
    - kubectl config set-context ci --cluster=k8s --user=ci
    - kubectl config use-context ci
    - helm upgrade --install $CI_PROJECT_PATH_SLUG .helm
        --set image=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME
        --set imageTag=$CI_COMMIT_REF_SLUG.$CI_PIPELINE_ID
        --debug
        --namespace $CI_PROJECT_PATH_SLUG-$CI_ENVIRONMENT_NAME
  only:
    - master

