#!/usr/bin/env bash

set -o pipefail
set -o nounset

docker_conf_file='/etc/sysconfig/docker'
is_restart_req=false
host=""


function usage
{
    echo "usage: $0 -host hostname | [-h | --help]"
}

#Handle command line arguments
while [ $# -gt 0 ]; do
    case $1 in
        -host )                 shift
                                eval "host=$1"
                                ;;
        -h | --help )           usage
                                exit
                                ;;
    esac
    shift
done

function init_insecure_reg()
{
    if grep -q '# INSECURE_REGISTRY' ${docker_conf_file}
    then
        sed -i.orig "/# INSECURE_REGISTRY=*/c\INSECURE_REGISTRY=\"\"" ${docker_conf_file}
        # Get machine IP address
        eval "openshift_subdomain=${OPENSHIFT_SUBDOMAIN}"
        local registry_host_name="hub.openshift.${openshift_subdomain}"
        sed -i.back "s/INSECURE_REGISTRY=\"\(.*\)\"/INSECURE_REGISTRY=\"\1 --insecure-registry 172.30.0.0\/16 --insecure-registry $registry_host_name\"/" ${docker_conf_file}
        is_restart_req=true
    fi
}

function append_insecure_reg()
{
    local host=$1
    local orig_str=`grep '^INSECURE_REGISTRY' ${docker_conf_file}`

    #Check if the host is already part of insecure registry, if not add it
    if ! echo ${orig_str} | grep -q ${host}
    then
        local replace_str="INSECURE_REGISTRY=\""
        local add_str="INSECURE_REGISTRY=\" --insecure-registry ${host}"
        local result_str="${orig_str/$replace_str/$add_str}"

        #Put the result string in the ${docker_conf_file}
        sed -i.back "s|${orig_str}|${result_str}|" ${docker_conf_file}
        is_restart_req=true
    fi
}

#Main
init_insecure_reg
if ! test -z $host ; then
    append_insecure_reg ${host}
fi

#Restart the docker demon if $is_restart_req is set to true
if [ "$is_restart_req" = true ] ; then
    systemctl restart docker
fi
