#!/bin/bash
#---------------------
# Testing nova-compute
#---------------------
set -e
DAEMONS=('nova-compute-kvm' 'nova-compute-lxc' 'nova-compute-qemu' 'nova-compute-ironic')
failure=false

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

# Set up the database for nova services.
# nova-compute requires nova-conductor to be running and responsive
# (it blocks in wait_until_ready() during startup). Conductor needs a
# synced database to start its RPC server.
mysql -u root << EOF
CREATE DATABASE IF NOT EXISTS nova;
CREATE DATABASE IF NOT EXISTS nova_api;
CREATE USER IF NOT EXISTS 'nova'@'localhost' IDENTIFIED BY 'changeme';
CREATE USER IF NOT EXISTS 'nova'@'%' IDENTIFIED BY 'changeme';
GRANT ALL PRIVILEGES ON nova.* TO 'nova'@'localhost';
GRANT ALL PRIVILEGES ON nova.* TO 'nova'@'%';
GRANT ALL PRIVILEGES ON nova_api.* TO 'nova'@'localhost';
GRANT ALL PRIVILEGES ON nova_api.* TO 'nova'@'%';
EOF

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

su -s /bin/sh -c 'nova-manage api_db sync' nova
su -s /bin/sh -c 'nova-manage db sync' nova

# Ensure nova-conductor is running
systemctl restart nova-conductor || service nova-conductor restart || true
sleep 5

for daemon in "${DAEMONS[@]}"; do
    apt-get install -y nova-compute $daemon 2>&1

    TIMEOUT=50
    while [ "$TIMEOUT" -gt 0 ]; do
        if pidof -x nova-compute > /dev/null; then
            echo "OK"
            break
        fi
        TIMEOUT=$((TIMEOUT - 1))
        sleep 0.1
    done

    if [ "$TIMEOUT" -le 0 ]; then
        echo "ERROR: NOVA-COMPUTE FOR $daemon IS NOT RUNNING"
        echo "/var/log/nova/nova-compute.log:"
        cat /var/log/nova/nova-compute.log
        echo "journalctl -u nova-compute --no-pager -n 50:"
        journalctl -u nova-compute --no-pager -n 50 || true
        failure=true
    else
        echo "NOVA-COMPUTE FOR $daemon IS RUNNING"
    fi

    apt-get remove -y $daemon nova-compute 2>&1
done

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