#!/bin/bash

# This script installs Deny Host, and useful SSH monitoring daemon.

################################################################################
#
# This script distributed free of charge by HildoerSystems.com
#
# This script comes with no warranty or guarantee. Please review the script
# before you run it to ensure that it will not cause adverse effects on your
# system.
#
# If you have any questions or comments, please e-mail: Anthony@HildoerSystems.com
#
################################################################################

sudo echo

if [ -f /etc/init.d/denyhosts ]; then
	echo Removing existing init scripts
	sudo /etc/init.d/denyhosts stop
	sudo rm -rf /etc/init.d/denyhosts
	sudo update-rc.d denyhosts remove
	echo '*********************'
	echo 
fi 

if [ -d /usr/share/denyhosts/ ]; then
	echo Removing existing installation
	sudo rm -rf /usr/share/denyhosts
	echo '*********************'
	echo 
fi

echo Installing 'python' and dependencies.
sudo aptitude -y install python
echo '*********************'
echo

cd /tmp 

echo Downloading DenyHost
wget http://superb-east.dl.sourceforge.net/sourceforge/denyhosts/DenyHosts-2.6.tar.gz
echo '*********************'
echo

echo Unpacking DenyHost
tar -xzf DenyHosts-2.6.tar.gz

directory=`ls -l | grep '^d' | grep 'DenyHosts-' | sed 's/\s\s*/ /g' | cut -f8 -d' ' | sort -n | tail -1`

cd $directory 
echo '*********************'
echo

echo Installing DenyHost
sudo python setup.py install
echo '*********************'
echo

cd /usr/share/denyhosts

echo Configuring DenyHost
sudo cp denyhosts.cfg-dist denyhosts.cfg
sudo sed -i.bak 's/^\s*\(SECURE_LOG\s*=.*\)$/#\1/' denyhosts.cfg
sudo sed -i.bak 's/^\s*#\s*SECURE_LOG\s*=\s*\/var\/log\/auth.log/SECURE_LOG = \/var\/log\/auth.log/' denyhosts.cfg
sudo sed -i.bak 's/^\s*\(LOCK_FILE\s*=.*\)$/#\1/' denyhosts.cfg
sudo sed -i.bak 's/^\s*#\s*LOCK_FILE\s*=\s*\/var\/run\/denyhosts.pid/LOCK_FILE = \/var\/run\/denyhosts.pid/' denyhosts.cfg
sudo sed -i.bak 's/^\s*\(BLOCK_SERVICE\s*=.*\)$/#\1/' denyhosts.cfg
sudo sed -i.bak 's/^\s*#\s*BLOCK_SERVICE\s*=\s*ALL/BLOCK_SERVICE  = ALL/' denyhosts.cfg
echo '*********************'
echo

echo Configuring executable
sudo cp daemon-control-dist daemon-control
sudo sed -i.bak 's/^\(\s*DENYHOSTS_BIN\s*=\s\).*$/\1"\/usr\/bin\/denyhosts.py"/' daemon-control
sudo sed -i.bak 's/^\(\s*DENYHOSTS_LOCK\s*=\s\).*$/\1"\/var\/run\/denyhosts.pid"/' daemon-control
sudo sed -i.bak 's/^\(\s*DENYHOSTS_CFG\s*=\s\).*$/\1"\/usr\/share\/denyhosts\/denyhosts.cfg"/' daemon-control
sudo chown root daemon-control
sudo chmod 700 daemon-control
echo '*********************'
echo

echo Adding ddclient to rc scripts 
cd /etc/init.d
sudo ln -s /usr/share/denyhosts/daemon-control denyhosts
sudo update-rc.d denyhosts defaults 
echo '*********************'
echo

echo Deleting temporary files
sudo rm -rf /tmp/DenyHost*
echo '*********************'
echo

echo Starting DenyHost
sudo /etc/init.d/denyhosts start
echo '*********************'
echo

