#!/bin/bash

FILE=$1
prefix="dc_wwn"
# 可能被外部直接调用，导致环境变量读不到
if [ -z "$BAK_DIR" ];then
    source /unas/etc/dualcontroller/syncconf
fi

parse_wwn() {
    # 使用临时文件，避免直接编辑文件导致循环触发同步
    # 这边编辑完后对比原文件，只在发生变化时才同步过去
    # 注意不能删了建，避免原文件的inode发生变化
    source=$1
    target=$BAK_DIR$1
    tmpfile=`mktemp`
    cp $source $tmpfile
    for wwn in `grep -o '"wwn": *"[^"]*"' $source | awk -F'"' '{print $4}'`;do
        n=`/unas/sbin/dualcontroller/tool/wwns | awk "/$wwn/ {print NR}" | head -n1`
        if [ -z "$n" ];then
            n=`/unas/sbin/dualcontroller/tool/wwns 1 | awk "/$wwn/ {print NR}" | head -n1`
        fi
        if [ -n "$n" ];then
            sed -i "s/$wwn/$prefix$n/g" $tmpfile
        fi
    done
    cat $tmpfile > $target
    rm $tmpfile
}

real_wwn() {
    # 使用临时文件，避免直接编辑文件导致循环触发同步
    # 这边编辑完后对比原文件，只在发生变化时才同步过去
    # 注意不能删了建，避免原文件的inode发生变化
    source=$BAK_DIR$1
    target=$1
    tmpfile=`mktemp`
    cp $source $tmpfile
    for wwn_n in `grep -o "\"wwn\": *\"$prefix[^\"]*\"" $tmpfile | awk -F'"' '{print $4}'`;do
        n="${wwn_n#$prefix}"
        wwn=`/unas/sbin/dualcontroller/tool/wwns | sed -n "${n}p"`
        if [ -z "$wwn" ];then
            # 拿不到对应口wwn，可能尝试拿1号口
            wwn=`/unas/sbin/dualcontroller/tool/wwns | sed -n "1p"`
        fi
        if [ -n "$n" ];then
            sed -i "s/\b$wwn_n\b/$wwn/g" $tmpfile
        fi
    done
    # 比对文件，只在发生变化时才同步过去
    if ! diff <(jq --sort-keys . $tmpfile) <(jq --sort-keys . $target) >/dev/null;then
        cat $tmpfile > $target
    fi
    rm $tmpfile
}

# Active all LUNs
# This is not appropriate to put it here
vgchange -ay

if [ "$FILE" == "/etc/rtslib-fb-target/saveconfig.json" ];then
    parse_wwn /etc/rtslib-fb-target/saveconfig.json
elif echo "$BAK_DIR/etc/rtslib-fb-target/saveconfig.json" | grep -q "$FILE";then
    real_wwn /etc/rtslib-fb-target/saveconfig.json
elif [ "$FILE" == "/unas/etc/targetcli/fcsan.json" ];then
    parse_wwn /unas/etc/targetcli/fcsan.json
elif echo "$BAK_DIR/unas/etc/targetcli/fcsan.json" | grep -q "$FILE";then
    real_wwn /unas/etc/targetcli/fcsan.json
elif [ "$FILE" == "/unas/etc/targetcli/iscsi.json" ];then
    s=/unas/etc/targetcli/iscsi.json
    t="$BAK_DIR/unas/etc/targetcli/iscsi.json"
    if ! diff <(jq --sort-keys . $s) <(jq --sort-keys . $t) >/dev/null; then
        cat $s > "$t"
    fi
elif echo "$BAK_DIR/unas/etc/targetcli/iscsi.json" | grep -q "$FILE";then
    s="$BAK_DIR/unas/etc/targetcli/iscsi.json"
    t="/unas/etc/targetcli/iscsi.json"
    if ! diff <(jq --sort-keys . $s) <(jq --sort-keys . $t) >/dev/null; then
        cat $s > "$t"
    fi
fi
