#!/bin/bash
. /etc/tos/scripts/scripts

find_real_device() {
    local blk=$1
    echo "$blk" | egrep -q -E "^/dev/md[0-9]+" >/dev/null
    if [ $? -eq 0 ]; then
        is_lvm $blk
        if [ $? -eq 1 ]; then
            vgs=$(timeout 5 pvs -o vg_name $blk --noheadings 2>/dev/null | sed s/[[:space:]]//g)
            blk=$(timeout 5 vgs -o lv_path $vgs --noheadings 2>/dev/null | sed s/[[:space:]]//g)
        fi
    fi
    echo $blk
}

mount_device() {
    local blk=$1
    local fs=$(blkid -o value -s TYPE $blk)
    if [ "$fs" = "LVM2_member" ]; then
        local vgs=$(timeout 5 pvs -o vg_name $blk --noheadings 2>/dev/null | sed s/[[:space:]]//g)
        blk=$(timeout 5 vgs -o lv_path $vgs --noheadings 2>/dev/null | sed s/[[:space:]]//g)
        echo -e "$blk" | while read line; do
            AutoMountDeviceTwo $line
        done
    else
        AutoMountDeviceTwo $blk
    fi
}

mntVolume() {
    vgscan
    local devices=$(find_real_device $1)
    echo -e "$devices" | while read device; do
        local SORT=$(GetVolumeSort $device)
        if [ -z "$SORT" ]; then
            echo -e "blockdevice: $device\nError: can't get sort from /etc/volume/volume.conf" >&2
            return 1
        fi
        mount_device "$device"
    done
}

mntVolume $1