#!/bin/bash

if [ -z $MPS_PATH ];then
	MPS_PATH="/usr/milis/mps"
fi

if [ ! -z $1 ];then
	MPS_PATH="$1"
fi

if [ ! -d $MPS_PATH ];then
	echo "$MPS_PATH dizini mevcut değil!"
	exit 1
fi

# detect lua version
LUA_VERSION="$(echo "print(_VERSION)" | lua |  cut -d' ' -f2)"

cd $MPS_PATH/src

# lua kütüphanelerinin derlenip-yüklenmesi

# 0 temizlik 

ext_libdir="ext${LUA_VERSION}"

[ -d $MPS_PATH/lua/${ext_libdir} ] && mv $MPS_PATH/lua/${ext_libdir} $MPS_PATH/lua/${ext_libdir}.old
mkdir -p $MPS_PATH/lua/${ext_libdir}

# 1- luafilesystem
cd luafilesystem && make clean && make -f makefile${LUA_VERSION} && cp -rf src/*.so $MPS_PATH/lua/${ext_libdir}/ && make clean
cd -

# 2- luasocket
cd luasocket && make clean && MYCFLAGS=$CFLAGS MYLDFLAGS=$LDFLAGS make LUAV=${LUA_VERSION} linux
mkdir /tmp/pkg.socket
make DESTDIR=/tmp/pkg.socket LUAV=${LUA_VERSION} prefix=/usr install-unix
cp -rf  /tmp/pkg.socket/usr/lib/lua/${LUA_VERSION}/*  $MPS_PATH/lua/${ext_libdir}/
cp -rf  /tmp/pkg.socket/usr/share/lua/${LUA_VERSION}/*  $MPS_PATH/lua/${ext_libdir}/
rm -rf /tmp/pkg.socket
make clean
cd -

# 3- lua-sec ssl support
cd luasec && make clean && make linux DEFS="-DWITH_LUASOCKET -DOPENSSL_NO_SSL3"
mkdir /tmp/pkg.sec
make LUACPATH="/tmp/pkg.sec/usr/lib/lua/${LUA_VERSION}" LUAPATH="/tmp/pkg.sec/usr/share/lua/${LUA_VERSION}" install
cp -rf  /tmp/pkg.sec/usr/lib/lua/${LUA_VERSION}/*  $MPS_PATH/lua/${ext_libdir}/
cp -rf  /tmp/pkg.sec/usr/share/lua/${LUA_VERSION}/*  $MPS_PATH/lua/${ext_libdir}/
rm -rf /tmp/pkg.sec
make clean
cd -

# 4 strip shared objects
find $MPS_PATH -name '*.so' | xargs -I {} strip {}

# 5 temizlik
rm -rf $MPS_PATH/lua/${ext_libdir}.old

# exe
chmod +x $MPS_PATH/bin/mps*.lua
