#!/bin/bash
#

main(){
if [ $# -eq 0 ]; then
   echo "Change the edoc2 image label:"
   echo "Usage: sh $0 -f /opt/docker-compose.yml -i edoc2"
   echo "Change the all image label:"
   echo "Usage: sh $0 -f /opt/docker-compose.yml -i all"
   exit 101
fi

while getopts f:i: arg; do
    case "$arg" in
       f)
         compose=$OPTARG ;;
       i)
         svc=$OPTARG ;;
       ?)
         echo "Invalid parameter."
         exit 101;;
    esac
done

if [ ! -f "$compose" ]; then
      echo "docke compose file not exists."
      exit 101
fi

if [ "$svc" == "all" ]; then
    img=($(grep 'image:' $compose | grep -v '#' | grep '192.168.251.78' | awk '{print $NF}'))
else
    img=($(grep 'image:' $compose | grep -v '#' | grep '192.168.251.78' | awk '{print $NF}' | grep "${svc}:"))
fi

if [ -n "$img" ]; then
    count=0
    for i in "${img[@]}"; do
        name=${i##*/}
        docker tag $i $name
        if [ $? -eq 0 ]; then
            echo "reset image tag [$i] to [192.168.251.78/edoc2v5/$name] success."
            let count++
        else
            echo "reset image tag [$i] to [192.168.251.78/edoc2v5/$name] falied."
        fi
    done
fi

if [ $count -eq ${#img[@]} ]; then
   echo "all image reset tag success, begin modify docker-compose file."
   sed -i.bak-$(date +%F) 's/registry.edoc2.com:5000/192.168.251.78/g' $compose
   echo "the old docker-compose file backup to ${compose}.bak-$(date +%F)"
fi

}

main $@
