#!/bin/bash
set -e

# Testing ironic-daemons
#---------------------
DAEMONS=('ironic-api' 'ironic-conductor')

ret=0

timeout_loop () {
    local TIMEOUT=90
    while [ "$TIMEOUT" -gt 0 ]; do
        if "$@" > /dev/null 2>&1; then
            echo "OK"
            return 0
        fi
        TIMEOUT=$((TIMEOUT - 1))
        sleep 1
    done
    echo "ERROR: $* FAILED"
    ret=1
    return 1
}

log_mysql_fail_and_exit() {
    echo "----- mysql.service status -----"
    systemctl status mysql.service || true
    echo "----- journalctl -u mysql -----"
    journalctl -u mysql.service --no-pager -n 200 || true
    echo "----- /var/log/mysql/error.log -----"
    [ -f /var/log/mysql/error.log ] && tail -n 200 /var/log/mysql/error.log || true
    exit 1
}

ensure_mysql_up() {
    if [ ! -d /var/lib/mysql/mysql ]; then
        echo "MySQL data dir seems empty; initializing..."
        mysqld --initialize-insecure --user=mysql || log_mysql_fail_and_exit
        chown -R mysql:mysql /var/lib/mysql || true
    fi

    systemctl reset-failed mysql.service || true
    systemctl start mysql.service || log_mysql_fail_and_exit
    timeout_loop systemctl is-active mysql.service || log_mysql_fail_and_exit

    if [ ! -S /var/run/mysqld/mysqld.sock ]; then
        sleep 2
        [ -S /var/run/mysqld/mysqld.sock ] || log_mysql_fail_and_exit
    fi
}

# Bring MySQL up reliably (LP: #2064930)
ensure_mysql_up

# Create DB + users
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

# Stop daemons if running
for daemon in "${DAEMONS[@]}"; do
    systemctl stop "$daemon" || true
done

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

# Run DB migrations
ironic-dbsync --config-file /etc/ironic/ironic.conf create_schema

# Start daemons and wait until active
for daemon in "${DAEMONS[@]}"; do
    systemctl start "$daemon"
    timeout_loop systemctl is-active "$daemon"
done

# Check API is responding
timeout_loop curl --fail http://localhost:6385
if [ "$ret" -eq 1 ]; then
    # Surface body if it failed
    curl http://localhost:6385 || true
fi

exit "$ret"
