version: 2
jobs:
  build:
    docker:
      - image: node:8

    working_directory: ~/repo

    environment:
      - STAGING_BRANCH: develop
      - PRODUCTION_BRANCH: master
      - DOCKER_IMAGE: ram-frontend
      - DOCKER_ORG: wbtransport
      - GH_REF: git@github.com:WorldBank-Transport/ram-backend.git
      - GH_NAME: "Development Seed"
      - GH_EMAIL: "dev@developmentseed.org"

    steps:
      - checkout

      - add_ssh_keys:
          fingerprints:
            - "ed:c1:81:ac:c3:74:2f:61:0c:8e:40:fd:7a:f2:7e:07"

      - run:
          name: Build Docker image for dev version
          command: |
            if [ "${CIRCLE_BRANCH}" == "${STAGING_BRANCH}" ]; then
              echo "Building Docker image"
              docker build -t "${DOCKER_IMAGE}" .
              docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWD

              echo "Pushing image to Docker Hub as :latest-dev"
              docker tag "${$DOCKER_IMAGE}" "${DOCKER_ORG}"/"${DOCKER_IMAGE}":latest-dev
              docker push "${DOCKER_ORG}"/"${DOCKER_IMAGE}":latest-dev
            else
              echo "This is not the "${STAGING_BRANCH}" branch. No need to build and push latest-dev."
            fi
      - deploy:
          name: Build Docker image for stable version
          command: |
            if [ "${CIRCLE_BRANCH}" == "${PRODUCTION_BRANCH}" ]; then
              # Grab version from package.json and prepend with v (v0.5.0)
              VERSION=v$(grep -m1 version package.json | awk -F: '{ print $2 }' | sed 's/[", ]//g')
              
              # Attempt to add a git tag based on version in package.json. If
              # the tag already exists, git will fail and stop the build.
              if ! git tag "${VERSION}" master
              then
                echo >&2 "Failed to tag a new release, skipping build. Did you update the version in package.json?"
                exit 1
              else
                # Push tag to Github
                git push origin "${VERSION}"

                echo Building Docker image
                docker build -t "${DOCKER_IMAGE}" .
                docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWD

                echo Pushing image to Docker Hub with "${VERSION}" tag
                docker tag "${$DOCKER_IMAGE}" "${DOCKER_ORG}"/"${DOCKER_IMAGE}":"${VERSION}"
                docker push "${DOCKER_ORG}"/"${DOCKER_IMAGE}":"${VERSION}"
              fi
            else
              echo "This is not the "${PRODUCTION_BRANCH}" branch. No need to build and push new version."
            fi
Move to Circle and use version numbers to tag Docker images
Move to Circle and use version numbers to tag Docker images
