#chkconfig: 2345 80 90
#description: sniper
#!/usr/bin/env bash

sniper_path=/usr/local/sniper

# 如果服务不存在，则需要执行安装脚本安装服务
if [ ! -d $sniper_path ] ; then
    echo "service sniper is not exist, you should run 'install.sh' srcipt"
    exit
fi

cd $sniper_path

case $1 in
    start)
        if [ -f /usr/local/sniper/startup.sh ] ; then
            chmod +x /usr/local/sniper/startup.sh
            /usr/local/sniper/startup.sh
        else
            driver_status=`lsmod | grep sniper | wc -l`
            if [ $driver_status == "0" ] ; then
                for kernel_module in sniperknl*.ko
                do
                    echo $kernel_module
                    insmod $kernel_module
                done
                if [ $? != 0 ] ;  then
                    echo "install sniper driver failed!!!"
                    exit -1
                fi
            fi
            ./sniper -d -o start
        fi
        ;;
    stop)
        if [ -f /usr/local/sniper/shutdown.sh ] ; then
            chmod +x /usr/local/sniper/shutdown.sh
            /usr/local/sniper/shutdown.sh
        else
            ./sniper -o stop
            rmmod sniperknl 2> /dev/null
        fi
        ;;
    status)
        driver_status=`lsmod | grep sniper | wc -l`
        if [ $driver_status == "0" ] ; then
            echo "sniper driver not installed"
        else
            echo "sniper driver is installed"
        fi
        /usr/local/sniper/sniper -s
        ;;
    register)
        basepath=$(cd `dirname $0`; pwd)
        echo "basepath: $basepath"
        if [ $# -lt 2 ] ; then
            echo "Usage: service ${server_name} register keybin-path"
        fi

        is_abs=`echo $2 | grep -e "^/.*" | wc -l`
        if [ "$is_abs" == "0" ] ; then
            echo "Usage: service ${server_name} register keybin-path, keybin-path must be an absolute path"
            exit 1
        fi 

        if [ ! -f $2 ] ; then
            echo "keybin: $2 not such file!!!"
            exit 1
        fi
        
        echo "copy keybin: $2 to $sniper_path/config"
        cp $2 $sniper_path/config
        ;;
    uninstall)
        ./sniper -o stop
        ./uninstall.sh
        ;;
    *)
        echo -e "Usage: service ${server_name} {start|stop|status|uninstall|register} ^_^\n" && exit ;;
esac
