#!/bin/bash
#---------------------
# Testing senlin-daemons
#---------------------
set -ex
DAEMONS=('senlin-api' 'senlin-engine')

for daemon in "${DAEMONS[@]}"; do
    systemctl stop $daemon
done

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

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

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
    timeout_loop "systemctl start $daemon"
    if [ "$ret" -eq 1 ]; then
        systemctl status $daemon
        journalctl -x --no-pager -u $daemon
    fi
    timeout_loop "systemctl is-active $daemon"
    if [ "$ret" -eq 1 ]; then
        systemctl status $daemon
        journalctl -x --no-pager -u $daemon
    fi
done

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