#!/bin/bash

function usage() {
    echo "Usage: ${0} <project> <version>"
    exit 1

}

# ----- Settings
Root=/opt/jupyter_gpu/pytorch/cvtt

LocalSoftwareDir=${Root}/software/cvtt2
ProdDir=${Root}/prod

ReleaseHosts=("cloud21.cvtt.vpn")
ReleasePorts=("22")
ReleaseUsers=("cvttdist")
ReleaseDir=("/home/cvttdist/software/cvtt2")
# ----- Settings

Project=${1}
Version=${2}

if [ "${Project}" == "" ]
then
    usage
fi

if [ "${Version}" == "" ]
then
    Version=latest
fi


function rsync_load_version() {
    for idx in "${!ReleaseHosts[@]}"
    do
        host=${ReleaseHosts[${idx}]}
        port=${ReleasePorts[${idx}]}
        user=${ReleaseUsers[${idx}]}
        rel_dir=${ReleaseDir[${idx}]}

        if [ "${Version}" == "latest" ]; then
            echo "Checking for latest version of ${Project} on ${user}@${host}:${rel_dir}"
            Version=$(ssh -q -p ${port} ${user}@${host} "ls -tr ${rel_dir}/${Project} | tail -1" )
            echo "Latest version is ${Version}"
        fi
        echo "Checking ${user}@${host} for ${rel_dir}/${Project}/${Version} ..."
        if ssh -q -p ${port} ${user}@${host} "test -d ${rel_dir}/${Project}/${Version}"
        then
            echo "Directory found..."
            rsync_cmd="rsync -ahvv -e \"ssh -p ${port}\""
            rsync_cmd="${rsync_cmd} ${user}@${host}:${rel_dir}/${Project}/${Version}"
            rsync_cmd="${rsync_cmd} ${LocalSoftwareDir}/${Project}/"
            echo ${rsync_cmd}
            eval ${rsync_cmd}
            status=$?
            if [ ${status} -eq 0 ]
            then
                echo "Loading successful..."
                break
            fi
        else
            echo "Not Found ${rel_dir}/${Project}/${Version} on ${user}@${host}"
        fi
    done
    if [[ ! -d ${LocalSoftwareDir}/${Project} ]] ; then
        echo ERROR loading software
        exit 1
    fi
}

mkdir -p ${LocalSoftwareDir}
mkdir -p ${ProdDir}

# exists and not empty
rsync_load_version

RelLocalSoftwareDir=../software/cvtt2
Location="${RelLocalSoftwareDir}/${Project}/${Version}/${Project}"

Cmd="cd ${ProdDir}"
Cmd="${Cmd} && rm -rf ${Project}"
Cmd="${Cmd} && ln -snf ${Location} ${Project}"

echo ${Cmd} && eval ${Cmd}

echo "Done: $0 $*"

