#!/bin/bash
#
# Copyright (c) 2006 Mellanox Technologies. All rights reserved.
#
# This Software is licensed under one of the following licenses:
#
# 1) under the terms of the "Common Public License 1.0" a copy of which is
#    available from the Open Source Initiative, see
#    http://www.opensource.org/licenses/cpl.php.
#
# 2) under the terms of the "The BSD License" a copy of which is
#    available from the Open Source Initiative, see
#    http://www.opensource.org/licenses/bsd-license.php.
#
# 3) under the terms of the "GNU General Public License (GPL) Version 2" a
#    copy of which is available from the Open Source Initiative, see
#    http://www.opensource.org/licenses/gpl-license.php.
#
# Licensee has the right to choose one of the above licenses.
#
# Redistributions of source code must retain the above copyright
# notice and one of the license notices.
#
# Redistributions in binary form must reproduce both the above copyright
# notice, one of the license notices in the documentation
# and/or other materials provided with the distribution.
#
#  $Id$
#

shopt -s nullglob

prog=/usr/bin/srp_daemon
params=("$@")
ibdir="/sys/class/infiniband"
rescan_interval=60
pids=()
pidfile="/run/srp_daemon.sh.pid"
mypid=$$

trap_handler()
{
    if [ "${#pids[@]}" ]; then
        kill -15 "${pids[@]}" > /dev/null 2>&1
        wait "${pids[@]}"
    fi
    logger -i -t "$(basename "$0")" "killing $prog."
    /bin/rm -f "$pidfile"
    exit 0
}

# Check if there is another copy running of srp_daemon.sh
if [ -f "$pidfile" ]; then
    if [ -e "/proc/$(cat "$pidfile" 2>/dev/null)/status" ]; then
        echo "$(basename "$0") is already running. Exiting."
        exit 1
    else
        /bin/rm -f "$pidfile"
    fi
fi

if ! echo $mypid > "$pidfile"; then
    echo "Creating $pidfile for pid $mypid failed"
    exit 1
fi

trap 'trap_handler' 2 15

while [ ! -d ${ibdir} ]
do
    sleep 30
done

for d in ${ibdir}_mad/umad*; do
    hca_id="$(<"$d/ibdev")"
    port="$(<"$d/port")"
    add_target="${ibdir}_srp/srp-${hca_id}-${port}/add_target"
    if [ -e "${add_target}" ]; then
        ${prog} -e -c -n -i "${hca_id}" -p "${port}" -R "${rescan_interval}" "${params[@]}" >/dev/null 2>&1 &
        pids+=($!)
    fi
done

wait
