#!/bin/bash
#-----------------------
# Testing cinder-daemons
#-----------------------
set -e
DAEMONS=('apache2' 'cinder-scheduler')
failure=false

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

sed -i -e 's!connection = sqlite.*cinder.sqlite!connection = mysql+pymysql://cinder:changeme@localhost/cinder!g' /etc/cinder/cinder.conf

su -s /bin/sh -c 'cinder-manage db sync' cinder

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

for daemon in "${DAEMONS[@]}"; do
    TIMEOUT=50
    while [ "$TIMEOUT" -gt 0 ]; do
        if pidof -x $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"
        failure=true
    else
        echo "${daemon} IS RUNNING"
    fi
done

if [ "$failure" = true ]; then
    exit 1
fi
