#!/bin/bash
set -e
[[ -z $1 ]] && echo "Usage: init_remote_wc.sh loadtest20190101.yaml" && exit -2
[[ -d $1 ]] && CFG="$1.yaml" || CFG=$1
[[ -f $1 ]] && WC=$(echo $1 | sed 's:.yaml::') || WC=$1

[[ -z $state ]] && state=1 # ansible-like 'target state'

source static/helpers.sh


kill_it() {
    set -x
    sky run -Up 'pkill -TERM -u $USER -f ".*'"$WORKDIR"'.*" && echo Killed' $BLINOV || [ 0 ]
    set +x
}

launch() {
    set -x
    sky run --mode i 'set -x; echo $INSTANCE_PORT > '"$WORKDIR"'/.instance_port' $BLINOV || [ 0 ]

    set +e
    for i in $(sky list $BLINOV | xargs); do 
        timeout -s TERM --foreground 30 \
            ssh $i "( ( nohup $WORKDIR/my_little_iss.sh $WORKDIR > $WORKDIR/nohup.out 2>&1 ) & ); echo Launcher started;" 
    done
}

SERVICE=$(fgrep target_mmeta $CFG | cut -f2 -d:)
echo "Resolving service $SERVICE"
BLINOV=$(get_blinov_for_service "$SERVICE")
echo "$( [[ $state == 1 ]] && echo 'Starting' || echo 'Stopping') Launcher for service $BLINOV"
WORKDIR=$(basename $WC)

kill_it
[[ "$state" -eq 1 ]] && launch

