#!/bin/bash -ex

install()
{
    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get -y \
        -o DPkg::Options::=--force-confdef \
        -o DPkg::Options::=--force-confold \
        install $@
}

# Set Hostname
HOSTNAME=mail
echo "$HOSTNAME" > /etc/hostname
sed -i "s|127.0.1.1 \(.*\)|127.0.1.1 $HOSTNAME.localdomain $HOSTNAME|" /etc/hosts
hostname mail

# Update package information
apt-get update

#Donwload iRedMail
apt-get -y install bzip2
wget http://iredmail.googlecode.com/files/iRedMail-0.6.1.tar.bz2
tar xf iRedMail-0.6.1.tar.bz2 -C /usr/local/src/

#Run iRedMail get_all script (to get tars)
cd /usr/local/src/iRedMail-0.6.1/pkgs/
bash get_all.sh
cd ..

#Install apache, mysql and webmin modules
install apache2 apache2-mpm-prefork apache2.2-common libapache2-mod-php5 libapache2-mod-auth-mysql php5-cli php5-imap php5-gd php5-mcrypt php5-mysql php5-ldap php5-common php-pear postfix postfix-pcre awstats mysql-server-5.1 mysql-client-5.1 postfix-mysql libapache2-mod-auth-mysql dovecot-imapd dovecot-pop3d amavisd-new libcrypt-openssl-rsa-perl libmail-dkim-perl clamav-freshclam clamav-daemon spamassassin altermime libmail-spf-perl acl patch cron tofrodos phpmyadmin webmin-dovecot webmin-postfix webmin-mysql

# Enable rewrite module
a2enmod rewrite

# Run freshclam to ensure that it finishes before creating the cdroot
freshclam

#Stop services
service apache2 stop
service mysql stop
service rsyslog stop
service postfix stop
service amavis stop
service cron stop
service dovecot stop 
service clamav-daemon stop
service clamav-freshclam stop

#Fix awstats call in crontab (bug in iRedMail script)
sed -i "s|/usr/lib/cgi-bin/awstats/awstats/awstats.pl|/usr/lib/cgi-bin/awstats/awstats.pl|" /var/spool/cron/crontabs/root

#Clean apt cache. 
apt-get clean
