#!/bin/bash
###########################################################################
#
# Description:  Patch Install Tool for Campus R21
# Version：        V1.0
# Author:       cwx598742
#
###########################################################################
#set -x
# Get node_ip_list
node_ip_list=`grep maintenance /opt/oss/manager/etc/sysconf/nodelists.json -C3 | grep IP | cut -d\" -f4`
echo $node_ip_list

SSHMGRPATH="/opt/oss/manager/tools/common/sshmgr" 


#==========================================================================
#   Name:           log
#   Description:    log to console and file
#   Input: String message
#   Return:
#==========================================================================
function log()
{
    timestamp=`date "+%Y-%m-%d %H:%M:%S"`
    message="$timestamp $@"
    echo -e $message >> ./patch_upgrade.log
}


#==========================================================================
#   Name:           Entrance
#   Description:    Main Function
#   Input: 
#   Return:
#==========================================================================
function main()
{
    log "-------- Update begin --------"
    
    chown -R ossadm:ossgroup /opt/Campus_SPC121_upgrade_patch
    for node_ip in ${node_ip_list[*]}
    do
       
        echo "copy zip for $node_ip"
        su - ossadm -c ". /opt/oss/manager/agent/bin/engr_profile.sh; sh $SSHMGRPATH/sshmgr.sh -exectype put -ip ${node_ip} -source /opt/Campus_SPC121_upgrade_patch/spc121_upgrade_patch.zip -target /opt/oss/" 
        echo "copy success"
        log "copy success for $node_ip"
        
        echo "Begin excute update operation for $node_ip, waiting..."
        su - ossadm -c ". /opt/oss/manager/agent/bin/engr_profile.sh; sh $SSHMGRPATH/sshmgr.sh -exectype cmd -ip ${node_ip} -cmd \"unzip -o /opt/oss/spc121_upgrade_patch.zip -d /opt/oss/spc121_upgrade_patch; find /opt/oss/spc121_upgrade_patch -type d -exec chmod 750 {} \; find /opt/oss/spc121_upgrade_patch -type f -name \"*.jar\" -exec chmod 640 {} \; sh /opt/oss/spc121_upgrade_patch/singleNoteUpdate.sh\""
            
        if [ $? -ne 0 ];then
            echo "[ERROR]Update Campus failed for $node_ip"
            exit 1
        else 
            echo "Update Campus to spc121 successfully for $node_ip"
            log "Update Campus to spc121 successfully for $node_ip"
        fi
        
    done
    
    
    echo "waiting 5 minutes to restart..."    
    log "waiting 5 minutes to restart..."    
    sleep 300
    log "Update to spc121 successfully"    
    log "-------- Update end --------"
    echo "Update to spc121 successfully"    
}

main "$@"


