#!/bin/bash
#
# description:	Fikker Webcache Bigbox Server.
# processname: fikkerd
# pidfile: ./logs/fikkerd.pid

prog="fikkerd"

start(){
	cd ./bin
	export LD_LIBRARY_PATH=$LD_LIBRARY_LD:.:../modules:../modules/webcache:../modules/shttp:../modules/portmap
    ulimit -c unlimited
    if [ -f "/usr/bin/pkill" ]; then
    /usr/bin/pkill fikkerd.monitor
    else
    pkill fikkerd.monitor
    fi
	./fikkerd.monitor 1> /dev/null 2> /dev/null &
	./fikkerd 1> /dev/null &
	ret=$?
	cd ..
	sleep 5
	if [ $ret -eq 0 ]; then
	    echo $"Starting $prog [OK]"
	else
    	echo $"Starting $prog [FAIL]"
    fi
    return $ret
}

stop(){
    if [ -f "/usr/bin/pkill" ]; then
    /usr/bin/pkill fikkerd.monitor
    else
    pkill fikkerd.monitor
    fi
    /bin/kill `cat ./logs/fikkerd.pid  2> /dev/null ` > /dev/null 2>&1
	ret=$?
	sleep 2
	if [ $ret -eq 0 ]; then
	    echo $"Stopping $prog [OK]"
	else
		if [ -f "/usr/bin/pkill" ]; then
	    /usr/bin/pkill fikkerd
	    else
	    pkill fikkerd
	    fi
    	echo $"Stopping $prog [FAIL]"
    fi	
	return $ret
}

restart(){
    stop
    echo $"Wait ..."
    sleep 5
    start
}

install(){
    cd service
    ./install.sh
    cd ..
}

uninstall(){
    cd service
    ./uninstall.sh
    cd ..
}

(echo "10240 65000" > /proc/sys/net/ipv4/ip_local_port_range) 1> /dev/null 2> /dev/null
(echo "120" > /proc/sys/net/ipv4/tcp_keepalive_time) 1> /dev/null 2> /dev/null
(echo "3" > /proc/sys/net/ipv4/tcp_syn_retries) 1> /dev/null 2> /dev/null
(echo "5" > /proc/sys/net/ipv4/tcp_retries2) 1> /dev/null 2> /dev/null
(echo "3" > /proc/sys/net/ipv4/tcp_orphan_retries) 1> /dev/null 2> /dev/null
(echo "30" > /proc/sys/net/ipv4/tcp_fin_timeout) 1> /dev/null 2> /dev/null
(echo "0" > /proc/sys/net/ipv4/tcp_tw_recycle) 1> /dev/null 2> /dev/null
(echo "1" > /proc/sys/net/ipv4/tcp_tw_reuse) 1> /dev/null 2> /dev/null
(echo "180000" > /proc/sys/net/ipv4/tcp_max_tw_buckets) 1> /dev/null 2> /dev/null
(echo "8192" > /proc/sys/net/ipv4/tcp_max_syn_backlog) 1> /dev/null 2> /dev/null
(echo "8192" > /proc/sys/net/core/somaxconn) 1> /dev/null 2> /dev/null
(echo "8192" > /proc/sys/net/core/netdev_max_backlog) 1> /dev/null 2> /dev/null

# Used For CentOS 6.X Version
if [ -f "/proc/sys/net/netfilter/nf_conntrack_max" ]; then
    (echo "1048560" > /proc/sys/net/netfilter/nf_conntrack_max) 1> /dev/null 2> /dev/null
    # echo "163840" > /proc/sys/net/netfilter/nf_conntrack_buckets
fi

# Used For CentOS 5.X Version
if [ -f "/proc/sys/net/ipv4/netfilter/ip_conntrack_max" ]; then
    (echo "1048560" > /proc/sys/net/ipv4/netfilter/ip_conntrack_max) 1> /dev/null 2> /dev/null
    # echo "163840" > /proc/sys/net/ipv4/netfilter/ip_conntrack_buckets
fi

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    restart
    ;;
  install)
    install
    ;;
  uninstall)
    uninstall
    ;;
  *)
    echo $"Usage: $0 {start|stop|install|uninstall|restart}"
    exit 1
esac

exit $?
