#!/bin/bash
#---------------------
# Testing manila-daemons
#---------------------
set -e
DAEMONS=('manila-api' 'manila-data' 'manila-scheduler' 'manila-share') 

ret=0

# Skip execution of tests if in a container
systemd-detect-virt --container && exit 0

# Manilla throws a traceback when running with sqlalchemy
debconf-set-selections <<EOT
mysql-server-5.7 mysql-server/root_password password rootpassword
mysql-server-5.7 mysql-server/root_password_again password rootpassword
EOT

DEBIAN_FRONTEND=noninteractive dpkg-reconfigure mysql-server-5.7

mysql --user=root --password=rootpassword <<EOT
create database manila
EOT


sed -i 's|#connection[ \t]*=.*|connection=mysql://root:rootpassword@127.0.0.1/manila?charset=utf8|' /etc/manila/manila.conf
manila-manage db sync

for daemon in "${DAEMONS[@]}"; do
    service $daemon restart;
done
sleep 5
for daemon in "${DAEMONS[@]}"; do
    TIMEOUT=50
    while [ "$TIMEOUT" -gt 0 ]; do
        if systemctl is-active $daemon > /dev/null; then
            echo "OK"
            break
        fi
        TIMEOUT=$((TIMEOUT - 1))
        sleep 0.1
    done

    if [ "$TIMEOUT" -le 0 ]; then
        echo "ERROR: ${daemon} IS NOT RUNNING"
        ret=1
    fi
done

exit $ret

