#!/bin/bash

CURRENT_FOLDER_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
SYS_VERSION=`rpm -q --queryformat '%{VERSION}' centos-release`

SS5_PORT="9999"
SS5_VERSION="3.8.9-8"
SS5_USER="ss5"
SS5_SOURCE_DIR="ss5-3.8.9"
SS5_TARBALL="ss5-$SS5_VERSION.tar.gz"
SS5_URL="http://downloads.sourceforge.net/project/ss5/ss5/$SS5_VERSION/$SS5_TARBALL?&use_mirror=heanet"
SS5_PATH="/etc/opt/ss5"

SS5_NVPN_PATCH="ss5-radius.patch"

TXT_RED=`tput setaf 1`
TXT_GREEN=`tput setaf 2`
TXT_RESET=`tput sgr0`

[ -d $SS5_SOURCE_DIR ] && rm -Rf ./$SS5_SOURCE_DIR
[ -e /etc/init.d/ss5 ] && /etc/init.d/ss5 stop 2>/dev/null 1>&2

if [ ! -e $SS5_TARBALL ]; then
echo "$TXT_GREEN * Downloading $SS5_URL $TXT_RESET"
wget -O $SS5_TARBALL -nv $SS5_URL
fi

echo "$TXT_GREEN * Unpacking $SS5_TARBALL $TXT_RESET"
tar -zxvf $SS5_TARBALL >/dev/null

echo "$TXT_GREEN * Patching SS5 $TXT_RESET"
patch -p0 < $SS5_NVPN_PATCH

echo "$TXT_GREEN * Configuring SS5 $TXT_RESET"
(yum -y install openldap-devel ; cd $SS5_SOURCE_DIR && ./configure --with-epollio) > /dev/null

echo "$TXT_GREEN * Building SS5 $TXT_RESET"
(cd $SS5_SOURCE_DIR && make) > /dev/null

echo "$TXT_GREEN * Installing SS5 to $SS5_INSTALL_DIR $TXT_RESET"
(cd $SS5_SOURCE_DIR && make install) > /dev/null

echo "$TXT_GREEN * Setting configuration $TXT_RESET"

cp ss5-radius.conf /etc/opt/ss5/ss5.conf
if [ $SYS_VERSION -eq 6 ]; then
 cp ss5 /etc/init.d/
 cp monit-ss5 /etc/monit.d
elif [ $SYS_VERSION -eq 7 ]; then
 cp ss5.service /lib/systemd/system/
 cp monit-ss5-systemd /etc/monit.d/monit-ss5
 if [ ! -d "/var/run/ss5" ]; then
     mkdir /var/run/ss5
 fi	
fi
 
chmod +x /etc/init.d/ss5

id $SS5_USER 2>/dev/null 1>&2 || useradd -s /sbin/nonexistent -M $SS5_USER
chown -R $SS5_USER $SS5_PATH
echo "SS5_OPTS=\" -u $SS5_USER -b 0.0.0.0:$SS5_PORT -m -t\"" > /etc/sysconfig/ss5
	
./build-stunnel.sh

if [ $SYS_VERSION -eq 6 ]; then
 /etc/init.d/ss5 start
 sleep 3
 /etc/init.d/monit restart
elif [ $SYS_VERSION -eq 7 ]; then
 systemctl enable ss5
 systemctl start ss5
 sleep 3
 systemctl restart monit
fi

if [[ "$*" == all ]]; then
/root/nvpn-ss5/obfsproxy/obfsproxy_setup.sh
echo "the SS5 setup is finished we proceed with SQUID"
sleep 5
cd /root/nvpn-squid/
./build.sh all
fi
