stages:
  - pubnub
  - build
  - deploy

set_prod:
  stage: pubnub
  script:
    - echo "ENV PUBNUB_PUB=$PUBNUB_PUB_PROD" >> Dockerfile
    - echo "ENV PUBNUB_SUB=$PUBNUB_SUB_PROD" >> Dockerfile
    - echo "ENV AGENT_TRACK_INTERVAL=180" >> Dockerfile
    - echo "ENV ABLY_KEY=$ABLY_PROD" >> Dockerfile
  artifacts:
    paths:
    - Dockerfile
  only:
    - master

set_dev:
  stage: pubnub
  script:
    - echo "ENV PUBNUB_PUB=$PUBNUB_PUB_DEV" >> Dockerfile
    - echo "ENV PUBNUB_SUB=$PUBNUB_SUB_DEV" >> Dockerfile
    - echo "ENV AGENT_TRACK_INTERVAL=180" >> Dockerfile
    - echo "ENV ABLY_KEY=$ABLY_DEV" >> Dockerfile
  artifacts:
    paths:
    - Dockerfile
  only:
    - dev

build:
  stage: build
  script:
    - cat Dockerfile
    - if [[ $CI_BUILD_REF_SLUG == 'master' ]]; then export ON_PROD='true'; else export ON_PROD='false'; fi
    - if [[ $CI_BUILD_REF_SLUG == 'master' ]]; then export NEW_RELIC_ENABLED='true'; else export NEW_RELIC_ENABLED='false'; fi
    - if [[ $CI_BUILD_REF_SLUG == 'master' ]]; then echo "ENV TRACK_OFFLINE_DEADLINE=60" >> Dockerfile; else echo "ENV TRACK_OFFLINE_DEADLINE=0" >> Dockerfile; fi
    - if [[ $CI_BUILD_REF_SLUG == 'master' ]]; then echo "ENV NODEJS_MEMORY_LIMIT=4096" >> Dockerfile; else echo "ENV NODEJS_MEMORY_LIMIT=1024" >> Dockerfile; fi
    - sed -i "s/https:\/\/gitlab.2-berega.ru/https:\/\/gitlab-ci-token:$CI_BUILD_TOKEN@dh-gitlab.cara.bi/g" package.json
    - echo "ENV PUBNUB_PUB2=pub-c-c02835d0-28eb-428d-aef4-28628d0d6794" >> Dockerfile
    - echo "ENV PUBNUB_SUB2=sub-c-4d8ada9e-1dbc-11e7-a5a9-0619f8945a4f" >> Dockerfile
    - echo "ENV GOOGLE_MAPS_KEY=$GOOGLE_MAPS_KEY" >> Dockerfile

    - echo "ENV NEW_RELIC_ENABLED=$NEW_RELIC_ENABLED" >> Dockerfile
    - echo "ENV NEW_RELIC_LICENSE_KEY=$NEW_RELIC_LICENSE_KEY" >> Dockerfile
    - echo "ENV NEW_RELIC_LABELS=branch:$CI_COMMIT_REF_NAME" >> Dockerfile
    - echo "ENV NEW_RELIC_APP_NAME=$CI_REGISTRY_IMAGE" >> Dockerfile
    - echo "ENV NEW_RELIC_NO_CONFIG_FILE=true" >> Dockerfile
    - echo "ENV ON_PROD=$ON_PROD" >> Dockerfile
    - cat Dockerfile
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - docker build --pull -t "$CI_REGISTRY_IMAGE:$CI_BUILD_REF_SLUG-$CI_PIPELINE_ID" -t "$CI_REGISTRY_IMAGE:$CI_BUILD_REF_SLUG-latest" .
    - docker push "$CI_REGISTRY_IMAGE:$CI_BUILD_REF_SLUG-$CI_PIPELINE_ID"
    - docker push "$CI_REGISTRY_IMAGE:$CI_BUILD_REF_SLUG-latest"

deploy_dev:
  stage: deploy
  script:
    - ssh $DEV_USER@$DEV_HOST kubectl set image deployment/geo geo="$CI_REGISTRY_IMAGE:$CI_BUILD_REF_SLUG-$CI_PIPELINE_ID"
  only:
    - dev

deploy_master:
  stage: deploy
  script:
    - ssh $PROD_USER@$PROD_HOST kubectl set image deployment/geo geo="$CI_REGISTRY_IMAGE:$CI_BUILD_REF_SLUG-$CI_PIPELINE_ID"
  only:
    - master
