#!/bin/bash
#---------------------
# Testing watcher-daemons
#---------------------
set -e
DAEMONS=('apache2' 'watcher-applier' 'watcher-decision-engine')

# The packages enable and auto-start the daemons at install time, before the DB
# is migrated. Stop them first, so they don't race the schema creation.
for daemon in "${DAEMONS[@]}"; do
    systemctl stop "${daemon}" || true
done

mysql -u root << EOF
CREATE USER 'watcher'@'localhost' IDENTIFIED BY 'changeme';
CREATE USER 'watcher'@'%' IDENTIFIED BY 'changeme';
CREATE DATABASE watcher;
GRANT ALL PRIVILEGES ON watcher.* TO 'watcher'@'localhost';
GRANT ALL PRIVILEGES ON watcher.* TO 'watcher'@'%';
EOF

crudini --set /etc/watcher/watcher.conf database connection "mysql+pymysql://watcher:changeme@localhost/watcher"

# Restrict to the compute collector as there is no keystone in the testbed
# for the storage collector to probes cinder via keystone during
# decision-engine startup.
crudini --set /etc/watcher/watcher.conf collector collector_plugins "compute"

watcher-db-manage upgrade

ret=0

timeout_loop () {
    TIMEOUT=100
    while [ "$TIMEOUT" -gt 0 ]; do
        if $1 > /dev/null 2>&1; then
            echo "OK"
            break
        fi
        TIMEOUT=$((TIMEOUT - 1))
        sleep 0.5
    done

    if [ "$TIMEOUT" -le 0 ]; then
        echo "ERROR: $1 FAILED"
        ret=1
    fi
}

for daemon in "${DAEMONS[@]}"; do
    systemctl restart $daemon
    timeout_loop "pidof -x $daemon"
done

timeout_loop "curl --fail http://localhost:9322/"
if [ "$ret" -eq 1 ]; then
    # Run curl one more time without --fail to ensure no silent failures
    curl http://localhost:9322
fi

exit $ret