#!/bin/bash -x
# A-A集群中的ZFS存储池必须开启multihost并由集群管理

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

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

if ! which zpool >/dev/null 2>&1; then
    echo "ZFS tools not found, skipping ZFS configuration"
    exit 0
fi

if [ "$RUNMODE" == "aa" ]; then
    # 不支持双活
    exit 0
fi

all_zpool() {
    zpool list -o name -H
}

pool_multihost_ok() {
    zpool get -H -o value multihost "$poolname" 2>/dev/null | grep -qx on
}

share_pool() {
    # 先在全部节点上导出，避免冲突
    /unas/sbin/dualcontroller/tool/nodes "zpool export '$poolname' 2>/dev/null || :"

    # 仅在本节点导入，开启 multihost
    # 后续别的流程还需要检查，不能export
    zpool import -f "$poolname"

    zfs set acltype=posixacl "$poolname"
    zfs set aclinherit=passthrough "$poolname"

    if pool_multihost_ok; then
        echo "Pool $poolname already has multihost=on"
    else
        echo "Enabling multihost for pool $poolname"
        zpool set multihost=on "$poolname"
    fi

    res_pool_name=ZFS_$(echo "$poolname" | sed 's/_/__/g')
    if $PCS resource config $res_pool_name; then
        echo "Resource $res_pool_name already exists, skipping"
    else
        echo "Creating PCS resource $res_pool_name for ZFS pool $poolname"
        $PCS resource create $res_pool_name ocf:heartbeat:ZFS \
            pool="$poolname" \
            op monitor interval=30s timeout=60s \
            op start  interval=0s  timeout=120s on-fail=ignore \
            op stop   interval=0s  timeout=120s
        $PCS constraint colocation add $res_pool_name with UNAS_Main_Node
        $PCS constraint order $res_pool_name then disk_ready kind=Optional
        $PCS constraint order $res_pool_name then mount_ready kind=Optional
    fi
}

for poolname in $(all_zpool);do
    share_pool
done
