stages:
    - setup
    - lint
    - test
    - publish
    - deploy

install:
    image: node:12
    stage: setup
    script:
        - npm ci
    artifacts:
        paths:
            - node_modules
        expire_in: 1 week

test:
    image: python:3.7
    stage: test
    needs: []
    services:
        - postgres:12
    variables:
        POSTGRES_DB: ci
        POSTGRES_USER: postgres
        POSTGRES_PASSWORD: postgres
        DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/$POSTGRES_DB"
        DB_HOST: postgres
    script:
        - python -V
        - pip install -r requirements.txt
        - python manage.py migrate --noinput
        - python manage.py createdefaultadmin
        - python manage.py test

lint:py:
    image: python:3.7
    stage: lint
    needs: []
    script:
        - pip install pycodestyle
        - pycodestyle --config=setup.cfg --count .

lint:js:
    image: node:alpine
    stage: lint
    needs: ["install"]
    script:
        - npm run lint:js

lint:md:
    image: node:alpine
    stage: lint
    needs: ["install"]
    script:
        - npm run lint:md

publish:
    stage: publish
    image: docker:stable
    needs: ["test", "lint:py", "lint:js", "lint:md"]
    services:
        - docker:stable-dind
    only:
        - develop
        - master
    script:
        - docker info
        - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
        - docker build . -t "$IMAGE_NAME"
        - docker push "$IMAGE_NAME"

deploy:dev:
    stage: deploy
    image: alpine:latest
    environment:
        name: dev
        url: http://api.dev.sik.party
    only:
        - develop
    variables:
        DOCKER_HOST: $DEV_CI_DOCKER_HOST
        DOCKER_TLS_VERIFY: 1
    before_script:
        - mkdir -p ~/.docker
        - echo "$DEV_TLSCACERT" > ~/.docker/ca.pem
        - echo "$DEV_TLSCERT" > ~/.docker/cert.pem
        - echo "$DEV_TLSKEY" > ~/.docker/key.pem
        - docker login -u gitlab-ci-token -p "$CI_BUILD_TOKEN" "$CI_REGISTRY"
    script:
        - docker stack deploy --with-registry-auth -c stack-compose-dev.yml "$SERVICE_NAME"
    after_script:
        - docker logout "$CI_REGISTRY"

deploy:production:
    stage: deploy
    image: docker:stable
    only:
        - master
    environment:
        name: production
        url: api.sika.sik.party
    when: manual
    variables:
        DOCKER_HOST: $CI_DOCKER_HOST
        DOCKER_TLS_VERIFY: 1
    before_script:
        - mkdir -p ~/.docker
        - echo "$TLSCACERT" > ~/.docker/ca.pem
        - echo "$TLSCERT" > ~/.docker/cert.pem
        - echo "$TLSKEY" > ~/.docker/key.pem
        - docker login -u gitlab-ci-token -p "$CI_BUILD_TOKEN" "$CI_REGISTRY"
    script:
        - docker stack deploy --with-registry-auth -c stack-compose.yml "$SERVICE_NAME"
    after_script:
        - docker logout "$CI_REGISTRY"