#!/bin/bash -x
# 配置挂载资源

# env:
#   DISK
#   MOUNTPOINT

if [ -z "$SSH" ];then
    source /unas/sbin/dualcontroller/config/prepare
fi

if [ -z "$PCS" ];then
    PCS=pcs
fi

lvm_res() {
    res_name=LV_$(lvs -a --options lv_full_name --noheading $DISK | sed 's/_/__/g;s#/#_#g;s/ //g')
    if $PCS resource config $res_name >/dev/null; then
        echo $res_name
    else
        res_name=VG_$(lvs -a --options vg_name --noheading $DISK | sed 's/_/__/g;s/ //g')
        if $PCS resource config $res_name >/dev/null; then
            echo $res_name
        else
            return 1
        fi
    fi
    return 0
}

get_disk_resource() {
    # 打印字符会被用于处理，所以只能输出资源名，不能有其他信息

    if [ ! -b "$DISK" ] && lvs "$DISK" >/dev/null 2>&1; then
        lvm_res
        return $?
    fi

    type=$(lsblk --output TYPE --noheadings $DISK | head -n1)
    case $type in
        disk)
            # 裸盘，不建议使用
            # 不需要colocation，直接创建文件系统资源即可
            return 1
            ;;
        lvm)
            # ocf::heartbeat::LVM-activate
            # ocf::heartbeat::LVM
            # 需要找到对应的LVM资源
            # 由于有两种可能的值，先尝试LVM-activate，如果找不到再尝试LVM
            lvm_res
            return $?
            ;;
        *)
            echo "Unknown disk type: $type" >&2
            return 1
            ;;
    esac
    return 1
}

if [ -b "$DISK" ] || lvs "$DISK"; then
    res_name="MNT$(echo $MOUNTPOINT | sed 's#/#_#g')"
    # 一般资源挂载失败也不要影响启动，所以失败策略设置为ignore
    $PCS resource create $res_name ocf:heartbeat:Filesystem \
        device="$DISK" directory="$MOUNTPOINT" fstype="none" options="nofail,defaults,usrquota,grpquota" \
        op monitor interval=10s \
        op start interval=0s timeout=120s on-fail=ignore
    if DISK_RES=$(get_disk_resource); then
        $PCS constraint colocation add $res_name with $DISK_RES
        $PCS constraint order disk_ready then $res_name
        $PCS constraint order $res_name then mount_ready
    else
        # Not required to colocation with a disk resource, just wait for the filesystem resource to be running
        # Or type not supported, just create the filesystem resource without colocation
        true
    fi
elif zfs list "$DISK" > /dev/null 2>&1;then
    # zfs，只需要改mountpoint，交给zfs自己管理
    zfs set mountpoint="$MOUNTPOINT" "$DISK"
    if [ "$MOUNTPOINT" == "/unas/etc/dualcontroller/cfg" ]; then
        # 创建一个假的MNT_unas_etc_dualcontroller_cfg，让后续服务依赖它，确保服务启动时配置盘已经挂载好
        $PCS resource create MNT_unas_etc_dualcontroller_cfg ocf:heartbeat:Dummy
        $PCS constraint colocation add MNT_unas_etc_dualcontroller_cfg with UNAS_Main_Node
        $PCS constraint order disk_ready then MNT_unas_etc_dualcontroller_cfg kind=Optional
        $PCS constraint order MNT_unas_etc_dualcontroller_cfg then mount_ready kind=Optional
    fi
else
    echo "Disk $DISK not found or not a block device" >&2
    exit 1
fi
