#!/bin/bash
set -eu

project_dir="${1:-}"
project_dir="${project_dir%%/}"
if [ -z "$project_dir" -o ! -d "${project_dir}/cmf" ]; then
    echo "${project_dir} должен быть проектом cmf!"
    exit 1
fi
project_name="${project_dir##*/}"

yum -y install epel-release
yum -y install nginx uwsgi uwsgi-devel python34 python34-devel python34-setuptools gcc
easy_install-3.4 pip
pip3.4 install -r "${project_dir}/cmf/requirements.txt"

(
	mkdir -p "${project_dir}/lib/uwsgi"
	cd "${project_dir}/lib/uwsgi"
	wget https://projects.unbit.it/downloads/uwsgi-2.0.15.tar.gz
	tar -xf uwsgi-2.0.15.tar.gz
	cd uwsgi-2.0.15
	python3 uwsgiconfig.py --build
	python3 uwsgiconfig.py --plugin plugins/python core python34
	#mkdir -p /usr/lib64/uwsgi/
	#cp -a ./python34_plugin.so /usr/lib64/uwsgi/
)

mkdir -p "${project_dir}/system/"
cp -a "${project_dir}/cmf/contrib/setup_nginx_uwsgi/nginx.conf" "${project_dir}/system/${project_name}_nginx.conf"
cp -a "${project_dir}/cmf/contrib/setup_nginx_uwsgi/upstart.conf" "${project_dir}/system/${project_name}_uwsgi.conf"

sed -i "s#{{PROJECT_PATH}}#$project_dir#g" "${project_dir}/system/${project_name}_nginx.conf"
sed -i "s#{{PROJECT_NAME}}#$project_name#g" "${project_dir}/system/${project_name}_nginx.conf"
sed -i "s#{{PROJECT_PATH}}#$project_dir#g" "${project_dir}/system/${project_name}_uwsgi.conf"
sed -i "s#{{PROJECT_NAME}}#$project_name#g" "${project_dir}/system/${project_name}_uwsgi.conf"

ln -f -s "${project_dir}/system/${project_name}_nginx.conf" /etc/nginx/conf.d/${project_name}_nginx.conf
ln -f -s "${project_dir}/system/${project_name}_uwsgi.conf" /etc/init/${project_name}_uwsgi.conf
initctl reload-configuration
initctl start ${project_name}_uwsgi
chkconfig nginx on
/etc/init.d/nginx restart
