#!/bin/bash

function check_multipath_status() {
    # Check service activity
    if ! systemctl is-active --quiet multipathd; then
        echo "Multipath service is not active"
        return 1
    fi

    # Get the list of devices
    MULTIPATH_DEVS=$(multipath -ll 2>/dev/null | grep -c 'dm-')

    # Save the initial number of devices
    if [ -z "$INITIAL_DEVICES" ]; then
        INITIAL_DEVICES=$MULTIPATH_DEVS
    fi

    # Check that devices are available
    if [ "$MULTIPATH_DEVS" -lt "$INITIAL_DEVICES" ]; then
        echo "Available only $MULTIPATH_DEVS from $INITIAL_DEVICES)"
        return 1
    fi

    # Check the paths
    if multipath -ll 2>/dev/null | grep -q 'faulty\|shaky'; then
        echo "Not all paths are OK"
        return 1
    fi

    # Check that devices are ready
    if ! multipath -ll 2>/dev/null | grep -q 'ready running'; then
        echo "Devices are not ready"
        return 1
    fi

    return 0
}

function start_locks() {
    # just start the locks on all VGs
    /usr/sbin/vgchange --lock-start
    return 0
}

# check that multipath service is enabled and should be waited
if systemctl is-enabled multipathd >/dev/null 2>&1; then
    # Max waiting time in seconds
    MAX_WAIT=60
    # Waiting timeout in seconds
    WAIT_INTERVAL=5
    # Passed time in seconds
    elapsed=0

    echo "Waiting multipath initialization..."

    while true; do
        if check_multipath_status; then
            echo "All multipath devices are ready"
            break
        fi

        if [ "$elapsed" -ge "$MAX_WAIT" ]; then
            echo "Waitng timeout expired"
            break
        fi

        sleep "$WAIT_INTERVAL"
        elapsed=$((elapsed + WAIT_INTERVAL))
        echo "The next check in $WAIT_INTERVAL seconds... ($elapsed/$MAX_WAIT)"
    done
else
    echo "multipathd is not enabled - just start locks"
fi
# start locks
start_locks
echo "Brest_lvm locks started"