#!/bin/bash

SYS_VERSION=`rpm -q --queryformat '%{VERSION}' centos-release`

#SQUID_VERSION="3.3.1"

SQUID_VERSION="3.3.12"
SQUID_SOURCE_DIR="squid-$SQUID_VERSION"
SQUID_TARBALL="$SQUID_SOURCE_DIR.tar.gz"
SQUID_URL="http://www.squid-cache.org/Versions/v3/3.3/$SQUID_TARBALL"
SQUID_INSTALL_DIR=/opt/squid
SQUID_NVPN_PATCH="squid-nvpn-final.patch"

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

[ -d $SQUID_SOURCE_DIR ] && rm -Rf ./$SQUID_SOURCE_DIR

[ -d $SQUID_INSTALL_DIR ] && echo "$TXT_RED * Error$TXT_RESET: Existing installation found at $SQUID_INSTALL_DIR. Remove it first and continue" && exit 1


if [ ! -e $SQUID_TARBALL ]; then
echo "$TXT_GREEN * Downloading $SQUID_URL $TXT_RESET"
wget -nv $SQUID_URL
fi

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

echo "$TXT_GREEN * Patching Squid $TXT_RESET"
patch -p1 < $SQUID_NVPN_PATCH

echo "$TXT_GREEN * Configuring Squid $TXT_RESET"
(cd $SQUID_SOURCE_DIR && find . -exec touch {} \; && ./configure --prefix=$SQUID_INSTALL_DIR --enable-ssl --disable-wccp --enable-auth --enable-auth-basic --enable-ltdl-convenience) > /dev/null

echo "$TXT_GREEN * Building Squid $TXT_RESET"
(cd $SQUID_SOURCE_DIR && make -j 4) > /dev/null
#(cd $SQUID_SOURCE_DIR && make clean -j 4) > /dev/null

echo "$TXT_GREEN * Installing Squid to $SQUID_INSTALL_DIR $TXT_RESET"
(cd $SQUID_SOURCE_DIR && make install) > /dev/null

echo "$TXT_GREEN * Setting configuration $TXT_RESET"

cp squid.conf $SQUID_INSTALL_DIR/etc/

if [ $SYS_VERSION -eq 6 ]; then
  cp monit-squid /etc/monit.d
  cp squid.init /etc/init.d/squid
  chmod +x /etc/init.d/squid
  chkconfig --add squid
  chkconfig squid on
elif [ $SYS_VERSION -eq 7 ]; then
  cp monit-squid-systemd /etc/monit.d/monit-squid
  cp squid.service /lib/systemd/system
  systemctl daemon-reload
  systemctl enable squid
fi

chmod 0777 $SQUID_INSTALL_DIR/var/logs
chmod 0777 $SQUID_INSTALL_DIR/var/cache/

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

if [[ "$*" == all ]]; then
echo "SQUID install is finished, we sleep and proceed with Nagios installation.."
sleep 5
cd /root/nvpn/
./deploy.sh -M
fi
