#!/bin/bash
alias oc=${OC:-oc}

repo_dir="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )/.."

IMAGE_TAG=${IMAGE_TAG:-"quay.io/openshift/origin-elasticsearch-proxy:latest"}

function login_to_registry() {
    local savectx=$( oc config current-context )
    local token=""
    local username=""
    if [ -n "${PUSH_USER:-}" -a -n "${PUSH_PASSWORD:-}" ] ; then
        username=$PUSH_USER
        if [ "$username" = "kube:admin" ] ; then
            username=kubeadmin
        fi
        oc login -u "$username" -p "$PUSH_PASSWORD" > /dev/null
        token=$( oc whoami -t 2> /dev/null || : )
        oc config use-context "$savectx"
    else
        # see if current context has a token
        token=$( oc whoami -t 2> /dev/null || : )
        if [ -n "$token" ] ; then
            username=$( oc whoami )
        else
            # get the first user with a token
            token=$( oc config view -o go-template='{{ range .users }}{{ if .user.token }}{{ print .user.token }}{{ end }}{{ end }}' )
            if [ -n "$token" ] ; then
                username=$( oc config view -o go-template='{{ range .users }}{{ if .user.token }}{{ print .name }}{{ end }}{{ end }}' )
                # username is in form username/cluster - strip off the cluster part
                username=$( echo "$username" | sed 's,/.*$,,' )
            fi
        fi
        if [ -z "$token" ] ; then
            echo ERROR: could not determine token to use to login to "$1"
            echo please do `oc login -u username -p password` to create a context with a token
            echo OR
            echo set \$PUSH_USER and \$PUSH_PASSWORD and run this script again
            return 1
        fi
        if [ "$username" = "kube:admin" ] ; then
            username=kubeadmin
        fi
    fi
    docker login -u "$username" -p "$token" "$1" > /dev/null
}

function push_image() {
    skopeo copy --dest-tls-verify=false docker-daemon:"$1" docker://"$2"
}

registry_namespace=openshift-image-registry
registry_svc=image-registry
registry_host=$registry_svc.$registry_namespace.svc
if ! oc get namespace $registry_namespace ; then
    registry_namespace=default
    registry_svc=docker-registry
    # use ip instead
    registry_host=$(oc get svc $registry_svc -n $registry_namespace -o jsonpath={.spec.clusterIP})
fi

registry_port=$(oc get svc $registry_svc -n $registry_namespace -o jsonpath={.spec.ports[0].port})
if [ $registry_namespace = openshift-image-registry ] ; then
    # takes pod name in 4.0
    port_fwd_obj=$( oc get pods -n $registry_namespace | awk '/^image-registry-/ {print $1}' )
else
    # takes service in 3.11
    port_fwd_obj="service/$registry_svc"
fi