stages:
  - build
  - trigger

variables:
  IMAGE_NAME: thallian/confd-env

build:
  stage: build
  script:
    - docker login -u $DOCKER_USER -p $DOCKER_PASSWORD $DOCKER_REGISTRY
    - docker build -t $IMAGE_NAME:$CI_COMMIT_SHA .
    - docker build -t $IMAGE_NAME:$CI_COMMIT_REF_NAME .
    - docker build -t $IMAGE_NAME:latest .
    - docker push $IMAGE_NAME:$CI_COMMIT_SHA
    - docker push $IMAGE_NAME:$CI_COMMIT_REF_NAME
    - docker push $IMAGE_NAME:latest

trigger:
  stage: trigger
  script:
    - apk --no-cache add curl
    - |
      for TRIGGER in $(echo $TRIGGERS | tr [:space:] ' '); do
        trigger_token=$(echo $TRIGGER | tr [_] ' ' | awk -v N=1 '{print $N}')
        project_id=$(echo $TRIGGER | tr [_] ' ' | awk -v N=2 '{print $N}')
        curl -fs -X POST -F ref=master -F token=$trigger_token $CI_API_V4_URL/projects/$project_id/trigger/pipeline > /dev/null
      done
