#!/usr/bin/env bash

set -o pipefail
set -o nounset

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


function usage
{
    echo "usage: $0 [-r | --registry] | [-h | --help]"
}

#Handle command line arguments
while [ $# -gt 0 ]; do
    case $1 in
        -r | --registry )       shift
                                registry=$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}
    fi
}

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

    #Check if the registry is already part of insecure registry, if not add it
    if ! echo ${orig_str} | grep -q ${registry}
    then
        local replace_str="INSECURE_REGISTRY=\""
        local add_str="INSECURE_REGISTRY=\" --insecure-registry ${registry}"
        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 $registry ; then
    append_insecure_reg ${registry}
fi

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