#!/usr/bin/env bash

set -xeuo pipefail

# ensure env is set
KUBECONFIG=$KUBECONFIG
MINIO_ID=$MINIO_ID
MINIO_SECRET=$MINIO_SECRET

testbedname="testbed-rms-test"
RMS_PORT=8080

probe_rms() { # thanks https://stackoverflow.com/a/12321815
    local max_retry=10
    local current=0
    until [ $current -eq $max_retry ] || curl -s -f -o /dev/null "http://127.0.0.1:$RMS_PORT/ping"; do
        sleep $(( current++ ))
    done

    [ $current -lt $max_retry ]
}

start_rms() {
    sed -i "s#KUBECONFIG#$KUBECONFIG#" config/rms.yaml # replace KUBECONFIG
    ../bin/rms -port $RMS_PORT -config config/rms.yaml>/dev/null &

    probe_rms

    sed -i "s#$KUBECONFIG#KUBECONFIG#" config/rms.yaml # recover config file
}

kill_rms() {
    pkill -9 rms || echo
}

run_test() {
    tcctl testbed create -f testdata/testbed.yaml --config config/tcctl.yaml
    tcctl testbed list --config config/tcctl.yaml
    tcctl testbed renew $testbedname --lease 1h --config config/tcctl.yaml
    tcctl testbed auth $testbedname --config config/tcctl.yaml
    tcctl testbed complete $testbedname --type Success --config config/tcctl.yaml
    tcctl testbed delete $testbedname --config config/tcctl.yaml

    output=`tcctl testbed restore-monitor $testbedname --config config/tcctl.yaml 2>&1` # because tcctl will log to stderr
    restored_testbed=`echo $output | sed -n 's/^.*\(testbed-restore-monitor-[[:alnum:]]*\).*$/\1/p'`
    tcctl testbed delete $restored_testbed --config config/tcctl.yaml
}

cd "$(dirname "$0")"
kill_rms # in case last test exit on fail
start_rms
run_test
kill_rms
