#!/bin/bash
#---------------------
# Testing ironic-daemons
#---------------------
set -e
DAEMONS=('ironic-api' 'ironic-conductor')

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


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

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

ironic-dbsync --config-file /etc/ironic/ironic.conf create_schema

ret=0

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

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

for daemon in "${DAEMONS[@]}"; do
    systemctl start $daemon
    timeout_loop "systemctl is-active $daemon"
done

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