#!/bin/bash
if [ $# -lt 1 ]; then
    echo Usage: $0 logdir_path
    exit 1
fi
port=$(echo $CB_ALLOCATION | awk -F '"Port":' '{print $2}' | cut -d'}' -f1 | cut -d',' -f1)
# ip=$(hostname -I | awk {'print $1}')
ip=$(grep $(hostname -s) $CB_ENVDIR/hosts | awk '{print $1}')
token=$(echo $RANDOM | md5sum | head -c 32)
if grep -q ^pp $CB_ENVDIR/vncsub.yaml; then    
    message=/ajj/$ip/$port/$token
    webroot=$message
else
    webroot=/$token
    message="http://$ip:$port$webroot"
fi
workingdir=$HOME/.jupyter
if [ ! -d $workingdir ]; then
    mkdir -p $workingdir
    if [ $? != 0 ]; then
        echo 'ERROR: Cannot write to user home directory.'
       exit 1
    fi
fi
find $workingdir -type f -name '*.log' -mtime +30 -exec rm "{}" \;

logfile=$workingdir/tb$CB_JOBID.log

tensorboard --bind_all --port $port --path_prefix $webroot --logdir $1 > $logfile 2>&1 &
n=1
while true;do
    sleep 1
    grep -q http:// $logfile
    if [ $? == 0 ] || [ $n == 120 ]; then
        break;
    fi
    n=$((n+1))
done
if [ $n == 120 ]; then
    kill %1
    exit -1
fi
cpost -d "$message" $CB_JOBID > /dev/null 2>&1
while true; do
    sleep 2
    jobs %1 | grep Running 2>&1 > /dev/null
    if [ $? != 0 ]; then
        exit 0
    fi
done
