#!/bin/sh
# useful functions
# 2013-09-26 11:00 created by niujiuru

# export envionment variables
export_env()
{
  PATH="/bin:/sbin:/usr/bin:/usr/sbin"

  CWD=$(dirname $0)
  [ "${CWD%%[^/]*}" != "/" ] && CWD="${PWD}/${CWD}"

  export PATH CWD
}

# load module by name
# pass THIS_MODULE to module
# $1: module name
load_module()
{
  local module="$1"
  THIS_MODULE="${module}"
  . ${CWD}/modules/${module}
}

# load module & call module's method
# $1: module name
# $2: method name
# $...: method params
call_module()
{
  local module="$1"
  local method="$2"
  shift 2
  load_module "$module" && "$method" $*
  return $?
}

# return true if program is running
# $1: program's name
is_running()
{
  ps | grep -w "$1" | grep -v "grep" &>/dev/null
}

# kill program(s) by name
# $1: program name
kill_programs()
{
  local sig=${2:-15}
  for p in $(ps | grep -w "$1" | grep -v "grep" | awk '{print $1}')
  do
    kill -$sig $p
  done
}
