stages:
- build
- publish
- deploy
- docs
- mirror

variables:
  production_repo: ubleipzig/deployer
  staging_repo: services.ub.uni-leipzig.de:11443/bdd_dev/deployer
  alpha_repo: services.ub.uni-leipzig.de:11443/bdd_dev/deployer

docker_build:
  stage: build
  image: docker:latest
  services:
  - docker:dind
  script: |
    docker build --pull \
      --build-arg HTTP_PROXY=${HTTP_PROXY} \
      --build-arg HTTPS_PROXY=${HTTPS_PROXY} \
      --build-arg NO_PROXY=${NO_PROXY} \
      --build-arg http_proxy=${HTTP_PROXY} \
      --build-arg https_proxy=${HTTPS_PROXY} \
      --build-arg no_proxy=${NO_PROXY} \
      -t image \
      .
    docker save --output=image.tar.gz image
  artifacts:
    name: docker-image
    paths:
    - image.tar.gz
  tags:
    - docker

docker_publish_alpha:
  stage: publish
  image: docker:latest
  services:
  - docker:dind
  script: |
    test "${DOCKER_ALPHA_AUTH_CONFIG}" == "" && echo "docker-config does not exists, aborting!" && false
    mkdir -p ~/.docker && echo "$DOCKER_ALPHA_AUTH_CONFIG" >~/.docker/config.json
    docker load --input=image.tar.gz
    docker tag image ${alpha_repo}:alpha-${CI_COMMIT_REF_SLUG}
    docker push ${alpha_repo}:alpha-${CI_COMMIT_REF_SLUG}
  dependencies:
  - docker_build
  tags:
  - docker
  only:
  - branches
  except:
  - master

docker_publish_staging:
  stage: publish
  image: docker:latest
  services:
  - docker:dind
  script: |
    test "${DOCKER_STAGING_AUTH_CONFIG}" == "" && echo "docker-config does not exists, aborting!" && false
    mkdir -p ~/.docker && echo "$DOCKER_STAGING_AUTH_CONFIG" >~/.docker/config.json
    docker load --input=image.tar.gz
    docker tag image ${staging_repo}:staging
    docker push ${staging_repo}:staging
  dependencies:
  - docker_build
  tags:
  - docker
  only:
  - master

docker_publish_production:
  stage: publish
  image: docker:latest
  services:
  - docker:dind
  script: |
    test "${DOCKER_LIVE_AUTH_CONFIG}" == "" && echo "docker-config does not exists, aborting!" && false
    mkdir -p ~/.docker && echo "$DOCKER_LIVE_AUTH_CONFIG" >~/.docker/config.json
    docker load --input=image.tar.gz
    export version=`expr ${CI_COMMIT_TAG} ':' 'release/\(.\+\)'`
    export major_version=`expr ${version} ':' '\([^.]\+\)'`
    export minor_version=`expr ${version} ':' '[^.]\+\.\([^.]\+\)'`
    export patch_version=`expr ${version} ':' '[^.]\+\.[^.]\+\.\(.\+\)'`
    echo "major version ${major_version}, minor version ${minor_version}, patch version ${patch_version}"
    for tag in "latest" "${major_version}" "${major_version}.${minor_version}" "${version}";do
      docker tag image ${production_repo}:${tag}
      docker push ${production_repo}:${tag}
    done
  dependencies:
  - docker_build
  tags:
    - docker
  except:
  - branches
  only:
  - /^release\/.*/