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

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

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
    # NOTE(jamespage):
    # reset any failed units otherwise they will not start - this
    # can happen in the period of time between package install and
    # the database actually being created.
    systemctl reset-failed ${daemon}
    systemctl start ${daemon} || {
        journalctl -xe -u ${daemon}
        cat /var/log/cinder/*
        exit 1
    }
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
