#!/bin/sh
#
# @@@ START COPYRIGHT @@@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# @@@ END COPYRIGHT @@@
#
function rm_shm {
    lv_port_file=$1
    echo "Using Portfile $lv_port_file"
    declare -i lv_virtual_node
    let lv_virtual_node=`echo $lv_port_file | awk -F/ '{print $NF}' | cut -d '.' -f 3`
    lv_port_no=`cat $lv_port_file | cut -d ':' -f 2`
    #echo "lv_virtual_node=$lv_virtual_node"
    #echo "lv_port_no=$lv_port_no"
    if [ -e $SQ_PDSH ]; then
       printf -v shm_key '0x0001%04x' $lv_port_no
       printf -v shm_name '/SYSV0001%04x' $lv_port_no
    else
       printf -v shm_key '0x%1x001%04x' $lv_virtual_node $lv_port_no
       printf -v shm_name '/SYSV%1x001%04x' $lv_virtual_node $lv_port_no
    fi
    printf -v rms_shm_key '0x1000%04x' $lv_port_no
    shm_id=`ipcs -m | grep "$shm_key" | cut -d ' ' -f 2`
    rms_shm_id=`ipcs -m | grep "$rms_shm_key"| cut -d ' ' -f 2`
    if [ -z $shm_id ]; then
       return
    fi
    echo "Killing the following attached process to shared segment $shm_id"
    pids=`lsof | egrep "$shm_name" | awk '{print $2}'`
    echo $pids
    if [ -n "$pids" ]; then
       echo $pids | xargs kill -9
    fi
    if [ -n $shm_id ]; then
       echo "Removing monitor shared segment $shm_id"
       ipcrm -m $shm_id
    fi
    if [ -n $rms_shm_id ]; then
        echo "Removing rms shared segment $rms_shm_id"
       ipcrm -m $rms_shm_id
    fi
}

declare -i portFilesCount
let portFilesCount=`ls $TRAF_VAR/monitor.port.*.bak 2>/dev/null | wc -l`
if ( [ "$portFilesCount" '==' 0 ] ); then
   echo "Unable to get the monitor port number"
   exit 1
fi

portFiles=`ls $TRAF_VAR/monitor.port.*.bak`
for portFile in $portFiles; do
    rm_shm $portFile
done

exit 0
