image: python:3.9

#services:
#  - postgres:13

variables:
  POSTGRES_DB: kszkepzes
  CONTAINER_IMAGE: 'registry.kszk.bme.hu/kszk/devteam/$CI_PROJECT_NAME:$CI_COMMIT_REF_NAME'

cache:
  key: '$CI_JOB_NAME-$CI_COMMIT_REF_SLUG'
  paths:
    - .cache/pip
    - env/

stages:
  - Test and Flake8
  - Docker Build
  - deploy

Flake8:
  stage: Test and Flake8
  only:
    - dev
    - master
    - tags
  tags: [kszk]
  script:
    - python -V
    - python3 -m venv env
    - source env/bin/activate
    - pip install -r requirements/production.txt
    - flake8 --max-line-length=125 --exclude=src/kszkepzes,migrations,env

# TODO write tests
# Test:
#   stage: Test and Flake8
#   only:
#     - dev
#     - master
#   tags: [kszk]
#   variables:
#     DATABASE_URL: 'postgresql://postgres:postgres@postgres:5432/$POSTGRES_DB'
#     SECRET_KEY: 'secret'
#     AUTHSCH_KEY: 'secret'
#     AUTHSCH_SECRET: 'secret'
#   script:
#     - python -V
#     - python3 -m venv env
#     - source env/bin/activate
#     - pip install -r requirements/production.txt
#     - python src/manage.py test

Docker build to KSZK registry:
  stage: Docker Build
  tags: [kszk]
  only:
    - tags
  image:
    name: gcr.io/kaniko-project/executor:debug
    entrypoint: ['']
  script:
    - echo "{\"auths\":{\"registry.kszk.bme.hu\":{\"username\":\"$REGISTRY_USER\",\"password\":\"$REGISTRY_PASSWORD\"}}}" > /kaniko/.docker/config.json
    - /kaniko/executor --context $CI_PROJECT_DIR --dockerfile $CI_PROJECT_DIR/Dockerfile --destination $CONTAINER_IMAGE

Deploy to Kubernetes:
  stage: deploy
  image: alpine
  tags: [devteam]
  environment:
    name: master
  script:
    - apk add --no-cache curl
    - curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
    - chmod +x ./kubectl
    - mv ./kubectl /usr/local/bin/kubectl
    - kubectl version
    - cd k8s
    - sed -i "s|##IMAGETAG##|${CI_COMMIT_REF_NAME}|" deployment.yml
    # A kovetkezo ket sor egy undorito workaround a mindig valtozo init kontenerek miatt letrejovo es beakado replicasetek miatt. Pls replace, ha van jobb otlet.
    - kubectl delete deployment apache-static
    - kubectl delete deployment kszkepzes-backend
    - kubectl apply -f deployment.yml
  only:
    - tags
