#!/bin/bash

PATH_VCS_CONF_FILE="/etc/fabos/Dcmd/vcs.conf"
PATH_CLUSTER_CONF_FILE="/etc/fabos/Dcmd/cluster.conf"
PATH_FABOS_CONF_FILE="/etc/fabos/fabos.0.conf"
PATH_FCOE_CONF_FILE="/etc/fabos/Dcmd/vcs_set_mode.sh"
VCS_SET_MODE_LOG_FILE="/mnt/var/log/vcs_set_mode.log"

CUR_PARTITION=""
MNT_PARTITION="/mnt"

default_partition=
default_configUpdate=
default_log=
default_vcsid=
default_rbridgeid=
default_vcsmode=
default_keepbm=

ERROR_STATUS_USAGE=1
ERROR_STATUS_VCS_CONF=2
ERROR_STATUS_CLUSTER_CONF=3
ERROR_STATUS_RBRIDGE_CONF=4
ERROR_STATUS_PARTITION=5
ERROR_STATUS_VCS_MODE=6

VCS_SET_MODE_LOG_FILE="/mnt/var/log/vcs_set_mode.log"

set -u

usage()
{ 
    echo "Usage: $0 argument list" 1>&2; 
    echo " -p | --partition    Partition [0: first partition, 1: second partition]"
    echo " -l | --log          Log absolute path"
    echo " -u | --update       Use config update [0: not use, 1: use]"
    echo " -b | --keepbm       Keep baremetal flag [0: delete, 1: keep]"
    echo "[-v | --vcsid]       New VCS ID [>=0]"
    echo "[-r | --rbridgeid]   New Rbridge ID [>=1]"
    echo "[-m | --vcsmode]     New VCS Mode [0/1/2]"

    exit $ERROR_STATUS_USAGE;
}

ha_role()
{
    /fabos/cliexec/hashow | while read ha; do
        case $ha in
            *Local*Active*)
                return 1;
            ;;
            *Local*Standby*)
                return 0;
            ;;
            *"not supported"*)
                return 1;
            ;;
            *)
                return 0;
            ;;
        esac
    done
    return $?
}

get_dcm_mode()
{

    # 0: FC
    # 1: MC
    # 2: SA
    local vcsconfvalue="0000"
    local clusterconfvalue="0"
    local dcm_mode=0

    if [ -f '/etc/fabos/Dcmd/vcs.conf' ]
    then
        vcsconfvalue=`cat /etc/fabos/Dcmd/vcs.conf`
    fi

    if [ -f '/etc/fabos/Dcmd/cluster.conf' ]
    then
        clusterconfvalue=`cat /etc/fabos/Dcmd/cluster.conf`
    fi

    if [[( $vcsconfvalue != "0000" && $clusterconfvalue == "0" )]]; then
        dcm_mode=0
    elif [[( $vcsconfvalue != "0000" && $clusterconfvalue == "1" )]]; then
        dcm_mode=1
    elif [[( $vcsconfvalue == "0000" && $clusterconfvalue == "0" )]]; then
        dcm_mode=2
    else
        dcm_mode=-1
    fi

    echo "$dcm_mode"
}

_reset_vcs_conf()
{
    local new_vcsid="$1"
    local target_partition="$2"

    if [ -n "$new_vcsid" ]; then
        echo "_reset_vcs_conf: Set new vcs id" >> $default_log
        cp $target_partition$PATH_VCS_CONF_FILE $target_partition$PATH_VCS_CONF_FILE.bk
        printf "%04d" $new_vcsid > $target_partition$PATH_VCS_CONF_FILE.bk 
        mv $target_partition$PATH_VCS_CONF_FILE.bk $target_partition$PATH_VCS_CONF_FILE

		# Fix for FCOE commands not working
		if [ -f "$target_partition$PATH_FCOE_CONF_FILE" ] ; then
			date > $VCS_SET_MODE_LOG_FILE
			VCS_MODE=`cat $target_partition$PATH_VCS_CONF_FILE | head -n 1`
			if [ $VCS_MODE != "0000" ]; then
				$target_partition$PATH_FCOE_CONF_FILE  enable  $target_partition
			else
				echo "VCS Mode not enabled. VCS_MODE=$VCS_MODE" >> $VCS_SET_MODE_LOG_FILE
			fi
		else
			echo "VCS set mode script not found." >> $VCS_SET_MODE_LOG_FILE
		fi

    else
        echo "_reset_vcs_conf: Error! [new vcsid is empty]" >> $default_log
        exit $ERROR_STATUS_VCS_CONF 
    fi
}

_reset_cluster_conf()
{
    local new_cluster_conf="$1"
    local target_partition="$2"

    if [ -z "$new_cluster_conf" ]; then    
        echo "_reset_cluster_conf: Error! [new cluster conf is empty]" >> $default_log
        exit $ERROR_STATUS_CLUSTER_CONF

    elif [ "$new_cluster_conf" -eq 2 ]; then
        echo "_reset_cluster_conf: Error! [Cannot write vcsmode ($new_cluster_conf) to config file]" >> $default_log
        exit $ERROR_STATUS_CLUSTER_CONF

    else
        cp $target_partition$PATH_CLUSTER_CONF_FILE $target_partition$PATH_CLUSTER_CONF_FILE.bk
        echo "_reset_cluster_conf: Set new cluster conf" >> $default_log
        printf $new_cluster_conf > $target_partition$PATH_CLUSTER_CONF_FILE.bk     
        mv $target_partition$PATH_CLUSTER_CONF_FILE.bk $target_partition$PATH_CLUSTER_CONF_FILE
    fi
}

_reset_rbridge_id()
{
    local new_rbridge_id="$1"
    local use_config_update="$2"

    if [ -z "$new_rbridge_id" ] || [ -z "$use_config_update" ];then
        echo "_reset_rbridge_id: Error! [new_rbridge_id or use_config_update is empty]" >> $default_log
        exit $ERROR_STATUS_RBRIDGE_CONF
    fi

    current_rbridge_id=`/fabos/cliexec/config get fabric.domain 2`

    if [ $new_rbridge_id -eq $current_rbridge_id ]; then
        echo "_reset_rbridge_id: New rbridgeId is same as current rbridgeId [$current_rbridge_id]" >> $default_log 
    else
        echo "_reset_rbridge_id: New rbridgeId [$new_rbridge_id] is different than current rbridgeid [$current_rbridge_id]" >> $default_log
    fi

    /fabos/cliexec/config set fabric.domain 2 $new_rbridge_id
    /fabos/cliexec/config export $PATH_FABOS_CONF_FILE
    /fabos/cliexec/config export $MNT_PARTITION$PATH_FABOS_CONF_FILE

    if [ $use_config_update -eq 1 ]; then
        ha_role
        if [ $? == 1 ]; then
            echo "_reset_rbridge_id: This is active MM, use config update to sync values" >> $default_log
            /fabos/cliexec/config update
        else
            echo "_reset_rbridge_id: This is Standby MM, don't reset rbridge id" >> $default_log
        fi
    fi

}

_get_target_partition()
{
    if [ -z "$default_partition" ]; then
        echo "_get_target_partition: Error! [target partiion is not specified]" >> $default_log
        exit $ERROR_STATUS_PARTITION 
    elif [ "$default_partition" -eq 0 ]; then
        echo "$CUR_PARTITION"
    elif [ "$default_partition" -eq 1 ]; then
        echo "$MNT_PARTITION"
    else
        echo "_get_target_partition: Error! [target partition is unknown]" >> $default_log
        exit $ERROR_STATUS_PARTITION
    fi
}

_clean_files()
{

    local target_partition=$1

    echo "_clean_files: Begin on $target_partition partition" >> $default_log

    # Clean configuration
    # Extract webui tarball
    echo "_clean_files: Clean configuration and extract tarball on $target_partition partition" >> $default_log

    if [ "$target_partition" == "$MNT_PARTITION" ];then
        /usr/sbin/chroot $MNT_PARTITION /fabos/cliexec/cfgcleanup
        /usr/sbin/chroot $MNT_PARTITION tar -C /etc/confd -xzvf /etc/confd/docroot.tgz > /dev/null 2>&1
    else
        /fabos/cliexec/cfgcleanup
        tar -C /etc/confd -xzvf /etc/confd/docroot.tgz > /dev/null 2>&1 
    fi

    # Fix startup link

    echo "_clean_files: Fix startup link on $target_partition partition" >> $default_log
    rm -rf $target_partition/var/config/vcs/scripts/startup-config

    rm -rf $target_partition/etc/fabos/Dcmd/startupFile

    if [ "$default_vcsmode" -ne 2 ]; then
        ln -s /etc/fabos/Dcmd/defaultconfig.vcs $target_partition/etc/fabos/Dcmd/startupFile 2>> $default_log
    else
        ln -s /etc/fabos/Dcmd/defaultconfig.novcs $target_partition/etc/fabos/Dcmd/startupFile 2>> $default_log
    fi          

    # Other files need to be removed, copied, extracted

    echo "_clean_files: Clean DB, trc, log, xml and other directory on $target_partition partition" >> $default_log
    rm -rf $target_partition/etc/fabos/Dcmd/PrismDatabase.previous.pgd
    rm -rf $target_partition/etc/fabos/Ccmd/PrismDatabase.previous.pgd

    rm -rf $target_partition/etc/fabos/Dcmd/Dcmd.Linux.powerpc.trc*
    rm -rf $target_partition/etc/fabos/Ccmd/Ccmd.Linux.powerpc.trc*

    rm -rf $target_partition/etc/fabos/Dcmd/Dcmd.Linux.powerpc.pg_ctl.log*
    rm -rf $target_partition/etc/fabos/Ccmd/Ccmd.Linux.powerpc.pg_ctl.log*

    rm -rf $target_partition/var/confd/log/*

    rm -f $target_partition/etc/fabos/NosSmd/yangNew/.extraction_completed
    rm -f $target_partition/etc/fabos/NosSmd/yangNew/*.xml

    if [ -d $target_partition/etc/fabos/Dcmd/yang ]
    then
        rm -rf $target_partition/etc/fabos/Dcmd/yang
    fi

    if [ -d $target_partition/etc/fabos/Ccmd/yang ]
    then
        rm -rf $target_partition/etc/fabos/Ccmd/yang
    fi

    if [ -L $target_partition/etc/fabos/NosSmd/yang ]
    then
        rm -f $target_partition/etc/fabos/NosSmd/yang
    fi

    rm -f $target_partition/etc/fabos/Dcmd/disableschemaconversion;
    rm -f $target_partition/etc/fabos/Ccmd/disableschemaconversion;

	rm -f $target_partition/etc/fabos/Dcmd/vcs.conf.fwdl;

    mkdir -p $target_partition/etc/fabos/Dcmd/ConfigSnapshot/

    # Clean core files
    echo "_clean_files: Clean core files" >> $default_log
    rm -rf /core_files/*/*     

    sync;
    sync;
  
    echo "_clean_files: End on $target_partition partition" >> $default_log
}

set_all_default()
{

    local target_partition=$(_get_target_partition)

    if [ -n "$default_vcsmode" ] && [ "$default_vcsmode" -ne 2 ]; then
        _reset_vcs_conf        "$default_vcsid"           "$target_partition"
        _reset_rbridge_id      "$default_rbridgeid"       "$default_configUpdate"
        _reset_cluster_conf    "$default_vcsmode"         "$target_partition"
    elif [ "$default_vcsmode" -eq 2 ];then
        _reset_vcs_conf        "0"                        "$target_partition"
        _reset_rbridge_id      "1"                        "$default_configUpdate"
        _reset_cluster_conf    "0"                        "$target_partition"
    else
        echo "set_all_default: Error! [vcs mode is not valid]" >> $default_log
        exit $ERROR_STATUS_VCS_MODE
    fi

    # clean all configuration files
    _clean_files "$target_partition"
}

set_local_conf()
{
    local target_partition=$(_get_target_partition)

    if [ "$default_keepbm" -eq 0 ]
    then
        echo "set_local_conf: remove local.conf on partition $target_partition" >> $default_log
        rm -f $target_partition/etc/fabos/Dcmd/Dcmd.Linux.powerpc.local.conf
    else
        local bmentry="<AconfigName>VcsNodeLocalManagedObject*${default_rbridgeid}</AconfigName><AconfigValue><AVcsNodeLocalManagedObject><AbulkingId>0</AbulkingId><AbmFlag>false</AbmFlag></AVcsNodeLocalManagedObject></AconfigValue><AmanagedObjectName>VcsNodeLocalManagedObject</AmanagedObjectName><AownerNodeObjectId>0*0</AownerNodeObjectId>"
        local bmentry_size=${#bmentry}
        echo -n "$bmentry_size#$bmentry" > $target_partition/etc/fabos/Dcmd/Dcmd.Linux.powerpc.local.conf
        echo "set_local_conf: create bmFlag=false in local.conf on partition $target_partition" >> $default_log
    fi
}

set_global_conf()
{
    local target_partition=$(_get_target_partition)
    rm -f $target_partition/etc/fabos/Dcmd/Dcmd.Linux.powerpc.global.conf
    echo "set_global_conf: remove global.conf on partition $target_partition" >> $default_log
}

# main
OPTS=`getopt -o :p:l:u:v:r:m:b:h -l partition:log:update:vcsid:rbridgeid:vcsmode:keepbm -- "$@"`

if [ $? != 0 ]
then
    echo "Detect invalid options"
    usage
fi

eval set -- "$OPTS"

while true ; do
    case "$1" in
        -p|--partition) 
            default_partition=$2 
            shift 2
            ;;

        -l|--log) 
            default_log=$2; 
            shift 2
            ;;

        -u|--configUpdate)
            default_configUpdate=$2; 
            shift 2
            ;;

        -v|--vcsid) 
            default_vcsid=$2;
            shift 2
            ;;

        -r|--rbridgeid) 
            default_rbridgeid=$2;
            shift 2
            ;;

        -m|--vcsmode) 
            default_vcsmode=$2; 
            shift 2
            ;;

        -b|--keepbm) 
            default_keepbm=$2; 
            shift 2
            ;;

        -h|--help)
            usage
            ;; 

        --) shift;
            break
            ;;

        *)  usage
            ;;
    esac
done


# validate inputs

if [ -z "$default_partition" ];then 
    echo "Missing -p | --partition option"
    usage
elif [ "$default_partition" -ne 0 ] && [ "$default_partition" -ne 1 ];then
    echo "Partition is not valid"
    usage
fi

if [ -z "$default_configUpdate" ];then 
    echo "Missing -u | --configUpdate option"
    usage
elif [ "$default_configUpdate" -ne 0 ] && [ "$default_configUpdate" -ne 1 ];then
    echo "configUpdate is not valid"
    usage
fi

if [ -z "$default_keepbm" ];then 
    echo "Missing -b | --keepbm option"
    usage
fi

if [ -z "$default_vcsid" ];then 
    default_vcsid=`cat $PATH_VCS_CONF_FILE | sed 's/^0*//'`
    echo "Use current vcsid=$default_vcsid"
elif [ "$default_vcsid" -lt 0 ];then
    echo "vcsid is not valid"
    usage
fi

if [ -z "$default_rbridgeid" ];then 
    default_rbridgeid=`/fabos/cliexec/config get fabric.domain 2`
    echo "Use current rbridgeid=$default_rbridgeid"
elif [ "$default_rbridgeid" -lt 1 ];then
    echo "rbridgeid is not valid"
    usage
fi

if [ -z "$default_vcsmode" ];then 
    default_vcsmode=$(get_dcm_mode)
    echo "Use current vcsmode=$default_vcsmode"
elif [ "$default_vcsmode" -lt 0 ] || [ "$default_vcsmode" -gt 2 ];then
    echo "vcsmode is not valid"
else
    default_vcsmode=$(get_dcm_mode)
    echo "Use current vcsmode=$default_vcsmode"
    usage
fi

if [ "$default_vcsmode" -eq 2 ] && [ "$default_vcsid" -ne 0 ]; then
    echo "Error: vcsid has non-zero value in SA mode"
    usage
fi

if [ "$default_vcsmode" -ne 2 ] && [ "$default_vcsid" -eq 0 ]; then
    echo "Error: vcsid cannot be zero in FC/MC mode"
    usage
fi


echo "Arguments List:"
echo "Partition :           $default_partition"
echo "Log absolute path :   $default_log"
echo "Use config update :   $default_configUpdate"
echo "New VCS ID :          $default_vcsid"
echo "New Rbridge ID :      $default_rbridgeid"
echo "New VCS Mode :        $default_vcsmode"

set_all_default
set_local_conf
set_global_conf
rm -f /fabos/config/fea-conf
