#!/bin/bash
source /root/envsetup/envsetup.conf

#APT_CACHER_PWD=$(cat ${CONF} | egrep ^APT_CACHER_PWD | head -1 | awk -F "=" '{print$2}')
APT_CACHER_PWD=$(pwgen 12)

# installation cm
aptitude install -y campus-manager

# installation cache local
aptitude install -y apt-cacher-ng
# secure it
echo "AdminAuth: ${APT_CACHER_USER}:${APT_CACHER_PWD}" >> /etc/apt-cacher-ng/security.conf
service apt-cacher-ng restart

# proxy
if [ ${PROXY} = "1" ]
then
	if [ ${PROXY_AUTHENTICATION} = "1" ]
	then
# general settings
	echo "Proxy: http://${PROXY_USER}:${PROXY_PASSWD}@${PROXY_HTTP}:${PROXY_PORT}" >> /etc/apt-cacher-ng/acng.conf
	else
# general settings
	echo "Proxy: http://${PROXY_HTTP}:${PROXY_PORT}" >> /etc/apt-cacher-ng/acng.conf
	fi
fi

# configure nginx
python3 /root/envsetup/envsetup.py 7
# devrait être inutile mais pb constaté avec jenkins
sed -i "s@server_name skyreach;@server_name ${CM_SERVER_NAME};@" /etc/nginx/sites-available/skyreach.conf

#~mv /etc/nginx/sites-enabled/skyreach.conf.tmp /etc/nginx/sites-enabled/skyreach.conf
service nginx restart

# iptables rules for port 3142
DEBIAN_FRONTEND=noninteractive aptitude install -y iptables-persistent
update-rc.d iptables-persistent enable
iptables -A INPUT -p tcp -s localhost --destination-port 3142 -j ACCEPT
iptables -A INPUT -p tcp --destination-port 3142 -j DROP
service iptables-persistent save

LIG=$(grep -n "^iface lo inet loopback" /etc/network/interfaces | awk -F ":" '{print$1}')
LIG=$(( ${LIG} + 1 ))

sed -i "${LIG}i\pre-up iptables-restore < /etc/iptables/rules.v4" /etc/network/interfaces
