<?xml version='1.0' encoding='UTF-8'?>
<project>
  <actions/>
  <description></description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.model.ParametersDefinitionProperty>
      <parameterDefinitions>
        <hudson.model.TextParameterDefinition>
          <name>KUBECONFIG_CREDENTIALS</name>
          <description>Contents of .kubeconfig file containing API credentials</description>
          <defaultValue>
apiVersion: v1
kind: Config
clusters:
- cluster:
    server: https://172.17.42.1:8443
    insecure-skip-tls-verify: true
  name: master
contexts:
- context:
    cluster: master
    user: openshift-client
  name: master
current-context: master
users:
- name: openshift-client
</defaultValue>
        </hudson.model.TextParameterDefinition>
      </parameterDefinitions>
    </hudson.model.ParametersDefinitionProperty>
  </properties>
  <scm class="hudson.scm.NullSCM"/>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Shell>
      <command>
export OPENSHIFTCONFIG=.kubeconfig
echo "${KUBECONFIG_CREDENTIALS}" > "${OPENSHIFTCONFIG}"

TEST_ENDPOINT=`osc get services -n test | grep frontend-test | awk '{print $4":"$5}'`

REGISTRY_ENDPOINT=`osc get services | grep docker-registry | awk '{print $4":"$5}'`

# clean up existing test deployment
set +e
echo "Removing old test deployment"
TEST_RC_ID=`osc get -n test replicationController | grep frontend-test | awk '{print $1}'`
if [ ! -z $TEST_RC_ID ]; then
  osc delete -n test replicationController $TEST_RC_ID
fi

TEST_POD_ID=`osc get pod -n test | grep frontend-test | awk '{print $1}'`
if [ ! -z $TEST_POD_ID ]; then
  osc delete pod -n test $TEST_POD_ID
fi
set -e

# wait for old pod to be torn down
sleep 5

# trigger a build
echo "Triggering new application build and deployment"
osc start-build -n test ruby-test-build

# check that the build test image deployed successfully
set +e
rc=1
count=0
attempts=100

echo "Checking test deployment at $TEST_ENDPOINT"
while [ $rc -ne 0 -a $count -lt $attempts ]; do
  curl -s --connect-timeout 2 $TEST_ENDPOINT
  rc=$?
  if [ $rc -ne 0 ]; then
    count=$(($count+1))
    echo "Attempt $count/$attempts"
    sleep 5
  fi
done
set -e

if [ $count -eq $attempts ]; then
    echo "Failed to reach test deployment"
    exit 1
fi


# Tag the image into production
echo "Test deployment succeeded, rolling out to production..."

COMMIT=`curl -s http://$REGISTRY_ENDPOINT/v1/repositories/test/origin-ruby-sample/tags/test`
curl -s -X PUT  http://$REGISTRY_ENDPOINT/v1/repositories/test/origin-ruby-sample/tags/prod -d "$COMMIT"
      </command>
    </hudson.tasks.Shell>
  </builders>
  <publishers/>
  <buildWrappers/>
</project>