#!/bin/sh
#
echo "SCRIPT $0 starting"

clone_repo () {
    if [ ! -d ${DIR} ]
    then
        mkdir -p ${DIR}
    fi

    for i in ${REPO}
    do
        echo $i
        if [ ! -d ${DIR}/$i ]
        then
            echo $i
            cd ${DIR}
            git clone ${REPOSITE}/${i}.git
    #        GIT_SSH_COMMAND="ssh -o 'StrictHostKeyChecking no' -i ${KEYS}" git clone ${REPOSITE}/${i}.git
        fi
    done
}

####################
MYNAME=`uname -n`
DELETE_ONETIME=0
if [ -f /zz/zPrivate/secrets/.${MYNAME}.${USER}.private ]
then
    . /zz/zPrivate/secrets/.${MYNAME}.${USER}.private
    DELETE_ONETIME=1
else
    if [ -f /zz/zSyno/secrets/.${MYNAME}.${USER}.private ]
    then
        . /zz/zSyno/secrets/.${MYNAME}.${USER}.private
        DELETE_ONETIME=1
    else
        if [ ! -f /root/root.private ]
        then
            echo "GITUSER=YYYY" > /root/root.private
            echo "DOMAIN=DOMAIN" >> /root/root.private
            echo "PORT=PORT" >> /root/root.private
            echo "PRIVATE_KEYS=~/YYY/qwer.pub" >> /root/root.private
            echo "PRIVATE_REPO="x  y  x"" >> /root/root.private
            echo "PUBLIC_REPO="x y z"" >> /root/root.private

            echo "PRIVATE_SITE=ssh://git@${DOMAIN}:${PORT}/${GITUSER}" >> /root/root.private

            echo " Created onetime file in /root"
            echo " It will be deleted after next use"
            exit 1
        else
            . /root/root.private
            DELETE_ONETIME=1
        fi
    fi
fi


# set base directories
if [ $USER != "root" ]
then
    ZZ=~/git
    if [ ! -d ${ZZ} ]
    then
        mkdir -p ${ZZ}/private
        mkdir -p ${ZZ}/public
        mkdir -p ${ZZ}/docker
    fi
else
    ZZ=/zz
fi

REPOSITE=${DOCKER_SITE}
KEYS=${DOCKER_KEYS}

REPO=${DOCKER_REPO}
if [ $USER != "root" ]
then
    DIR=${ZZ}/docker
else
    DIR=${ZZ}
fi
clone_repo

# start cloning repos
REPOSITE=${PRIVATE_SITE}
KEYS=${PRIVATE_KEYS}

REPO=${PRIVATE_REPO}
if [ $USER != "root" ]
then
    DIR=${ZZ}/private
else
    DIR=${ZZ}
fi
clone_repo

REPO=${PUBLIC_REPO}
if [ $USER != "root" ]
then
    DIR=${ZZ}/public
else
    DIR=${ZZ}
fi
clone_repo

if [ ${DELETE_ONETIME} = 1 ]
then
    rm -f /root/root.private
    echo "Deleting /root/root.private"
fi

if [ $USER != "root" ]
then
    echo "not updating crontab"
else
	crontab -u root /zz/zPrivate/crontabs/DEBcrontab
fi

exit 0

