#!/bin/sh
#filename: memcached.sh
# Description: Install Memcache Script.
# Author: shuhui.qiu


# Define Variables
PREFIX='/usr/local'
PKG_DIR='/usr/local/src'
PHP_CONFIG=$(which php-config)
PHP_INI=$(php -i|grep "Loaded Configuration File"|awk '{print $5}')

# Make Thread 
cpu_threads=$(expr $(grep processor /proc/cpuinfo|wc -l) + 1)


if [ $(id -u) -ne 0 ];
then
	echo "ERROR,Please run as root user!";exit 1;
fi


function libevent() {
	cd ${PKG_DIR};
	wget -c http://down.vqiu.cn/package/tarball/memcached/libevent-2.0.22-stable.tar.gz;
	tar zxvf libevent-2.0.22-stable.tar.gz
	cd libevent-2.0.22-stable
	./configure --prefix=${PREFIX}/libevent;make -j${cpu_threads};make install
}

function re2c() {
	wget -c http://down.vqiu.cn/package/tarball/memcached/re2c-0.13.5.tar.gz;
	tar zxvf re2c-0.13.5.tar.gz
	cd re2c-0.13.5
	./configure;make -j${cpu_threads};make install
}

function memcached() {
	cd ${PKG_DIR};
	wget -c http://down.vqiu.cn/package/tarball/memcached/memcached-1.4.24.tar.gz;
	tar zxvf memcached-1.4.24.tar.gz
	cd memcached-1.4.24
	./configure \
	--prefix=${PREFIX}/memcached \
	--with-libevent=${PREFIX}/libevent \
	--with-64bit \
	--disable-docs
	make -j${cpu_threads};make install
	
	# Env Variables
	echo 'export PATH="$PATH:${PREFIX}/memcached/bin"' > /etc/profile.d/memcached.sh
	source /etc/profile.d/memcached.sh
	
	# Start memcached Service
	${PREFIX}/memcached/bin/memcached -m ${MEM} -u root -p 11211 -d
	echo "${PREFIX}/memcached/bin/memcached -m ${MEM} -u root -p 11211 -d" >> /etc/rc.local
}

function libmemcached() {
	cd ${PKG_DIR};
	wget -c http://down.vqiu.cn/package/tarball/memcached/libmemcached-1.0.18.tar.gz
	tar zxvf libmemcached-1.0.18.tar.gz
	cd libmemcached-1.0.18
	./configure \
	--prefix=${PREFIX}/libmemcached \
	--with-memcached=${PREFIX}/memcached/bin/memcached
	make -j${cpu_threads};make install
}

function php_memcached() {
	# Website http://pecl.php.net/package/memcached/2.2.0
	cd ${PKG_DIR};
	wget -c http://down.vqiu.cn/package/tarball/memcached/memcached-2.2.0.tgz;
	tar zxvf memcached-2.2.0.tgz;
	cd memcached-2.2.0
	phpize
	./configure \
	--with-php-config=${PHP_CONFIG} \
	--with-libmemcached-dir=${PREFIX}/libmemcached \
	--disable-memcached-sasl
	make -j${cpu_threads};make install
	echo -en '\n\n[memcached]\nextension = memcached.so' >> ${PHP_INI}
}


function php_memcache() {
	cd ${PKG_DIR};
	wget -c http://down.vqiu.cn/package/tarball/memcached/memcache-3.0.8.tgz;
	tar zxvf memcache-3.0.8.tgz;
	cd memcache-3.0.8
	phpize
	./configure \
	--with-php-config=${PHP_CONFIG}
	make -j${cpu_threads};make install
	echo -en '\n\n[memcache]\nextension = memcache.so' >> ${PHP_INI}
}
libevent
libmemcached
memcached
php_memcached
php_memcache
