#
# Copyright 2018 Shuouma <dreamcast-talk.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
# Description:
# Install script for DC Mail setup
# A DC -> Gmail Relay
# Dirty bash script that does the job
# Posfix to use SSL/TLS Gmail for SMTP
# FetchMail + ProcMail to fetch mail from Gmail
# Dovecot to serve the mail account with POP3 to DC
#

#!/bin/bash

function install_package {
pack=$1
problem=$(dpkg -s $pack|grep installed)
echo "##### Checking for $pack: $problem"
if [ "" == "$problem" ]; then
    echo "Missing $pack installing...[This may take a while]"
    DEBIAN_FRONTEND=noninteractive apt-get --force-yes --yes install $pack > /dev/null 2>&1
    rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi
fi
}

function create_postfix_main {
/etc/init.d/postfix stop > /dev/null 2>&1

echo '#DC POSTFIX CONFIG
myhostname = dreampi
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
mydestination = localhost.localdomain, localhost
mynetworks_style = subnet 
relayhost = [smtp.gmail.com]:587
mailbox_size_limit = 0
recipient_delimiter = +
inet_protocols = ipv4
inet_interfaces = all
home_mailbox = Maildir/
recipient_canonical_maps = hash:/etc/postfix/canonical-rcpt
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
smtp_sasl_security_options = noanonymous
smtp_use_tls = yes
smtpd_recipient_restrictions = permit_mynetworks, 
			       permit_sasl_authenticated,
                               reject_unauth_destination,
			       reject_rbl_client zen.spamhaus.org,
			       reject_rhsbl_reverse_client dbl.spamhaus.org,
			       reject_rhsbl_helo dbl.spamhaus.org,
			       reject_rhsbl_sender dbl.spamhaus.org
' > /etc/postfix/main.cf    
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi

echo 'stc@sega.co.jp xidensegafan@gmail.com
swirl@segaswirl.com shuoumadc@gmail.com
swirl_stats@segaswirl.com shuoumadc@gmail.com' > /etc/postfix/canonical-rcpt
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi

postmap /etc/postfix/canonical-rcpt
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi

}

function create_sasl {
username=$1
password=$2

echo "[smtp.gmail.com]:587 $username@gmail.com:$password" > /etc/postfix/sasl_passwd
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi
    
postmap /etc/postfix/sasl_passwd
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi
   
echo "Secure with better permission"
chown root:root /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi
    
chmod 0400 /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi

}

function create_fetchmail {
username=$1
password=$2

echo "#DC FETCHMAIL CONFIG
set postmaster \"$username\"
set daemon 600
	
poll pop.gmail.com with proto POP3
user \"$username@gmail.com\" there with password \"$password\" is $username here options ssl
fetchall
no keep
mda '/usr/bin/procmail -f %F -d %T';
" > /home/$username/.fetchmailrc
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi
   
chmod 0400 /home/$username/.fetchmailrc
chown $username:$username /home/$username/.fetchmailrc
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi
}

function create_procmailrc {
username=$1
echo '#DC PROCMAIL CONFIG
UMASK=007
PATH=/usr/bin:/usr/local/bin
MAILDIR=$HOME/Maildir/
DEFAULT=$HOME/Maildir/
LOGFILE=$HOME/procmail.log
SHELL=/bin/sh
:0 fwh
| formail -k                                                          \
          -X Date:                                                    \
          -X Subject:                                                 \
          -X Message-Id:                                              \
          -X From                                                     \
          -X To:                                                      \
          -X Cc:                                                      \
          -X Reply-To:                                                \
          -X Mime-Version:                                            \
          -X Content-type:
' > /home/$username/.procmailrc
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi

chown $username:$username /home/$username/.procmailrc
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi
}

function create_dovecot_config {
/etc/init.d/dovecot stop > /dev/null 2>&1

ip=$(ip route get 1 | awk '{print $NF;exit}')

echo "#DC DOVECOT CONFIG
disable_plaintext_auth = no
listen = *
login_trusted_networks = 127.0.0.1 $ip/24
mail_location = maildir:~/Maildir
passdb {
  driver = pam
}
protocols = pop3
ssl = no
userdb {
  driver = passwd
}
" > /etc/dovecot/dovecot.conf
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi

chown root:dovecot /etc/dovecot/dovecot.conf
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi

rm -f /etc/dovecot/conf.d/*
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi
}

function add_user {
username=$1
password=$2
   
echo "useradd $uservar" 
useradd $username > /dev/null 2>&1
echo $uservar:$password | chpasswd
mkdir /home/$username > /dev/null 2>&1
cp -rT /etc/skel /home/$username
mkdir /home/$username/Maildir > /dev/null 2>&1
chown -R $username:$username /home/$username
}

echo "##### DC Mail setup #####"

if [ "$EUID" -ne 0 ]
  then echo "Please run as root or sudo"
  exit
fi

# Backup the original sources.list file
cp /etc/apt/sources.list /etc/apt/sources.list.bak

# Modify the first line with the new repository URL
sed -i "1s@.*@$new_repo@" /etc/apt/sources.list

echo "####Repository URL has been updated:"
#head -n 1 /etc/apt/sources.list

echo "##### Apt-get update to resolve any bad mirrors [First time, may take a while ~8min]"
apt-get update > /dev/null 2>&1

echo "##### Install libsasl2-modules"
install_package libsasl2-modules
echo "##### Install postfix"
install_package postfix
create_postfix_main
install_package ca-certificates
echo "##### Install fetchmail & procmail"
install_package fetchmail
install_package procmail
echo "##### Install dovecot"
install_package dovecot-core
create_dovecot_config
install_package dovecot-pop3d
create_dovecot_config

echo -e
read -p '##### Enter your Gmail username (without @gmail.com): ' uservar
prompt='##### Enter your Gmail password [HIDDEN]: '
while IFS= read -p "$prompt" -r -s -n 1 char
do
    if [[ $char == $'\0' ]]
    then
        break
    fi
    prompt='*'
    passvar+="$char"
done
unset prompt
echo -e

prompt='##### Enter local POP password (Length < 16): '
while IFS= read -p "$prompt" -r -s -n 1 char
do
    if [[ $char == $'\0' ]]
    then
        break
    fi
    prompt='*'
    localpass+="$char"
done
echo -e

echo "###### Create /etc/postfix/sasl_passwd"
create_sasl $uservar $passvar
echo "###### Create user: $uservar with password provided"
add_user $uservar $localpass
echo "###### Create .fetchmailrc"
create_fetchmail $uservar $passvar
echo "###### Create .procmailrc"
create_procmailrc $uservar

echo "###### Start postfix and dovecot"
/etc/init.d/postfix start > /dev/null 2>&1
/etc/init.d/dovecot start > /dev/null 2>&1
update-rc.d postfix enable > /dev/null 2>&1
update-rc.d dovecot enable > /dev/null 2>&1

if ! grep -q "fetchmail" /var/spool/cron/crontabs/$uservar; then
    echo "##### Add fetchmail to cron"
    echo '*/5 * * * * /usr/bin/fetchmail -d0 &> /dev/null' > /var/spool/cron/crontabs/$uservar
fi

echo "###### Start cron"
chown $uservar:crontab /var/spool/cron/crontabs/$uservar
chmod 0600 /var/spool/cron/crontabs/$uservar
/etc/init.d/cron start > /dev/null 2>&1
update-rc.d cron enable > /dev/null 2>&1

ip=$(ip route | grep default | awk '{print $3}' | awk -F. '{print $1"."$2"."$3}')
echo "
##### INFO:
Email Login: $uservar
Email Password: [The password you entered in the local POP login question]
Email Address: $uservar@gmail.com
Incoming Server (POP3): $ip.98
Outgoing Server (SMTP): $ip.98
#### WE ARE DONE! #####"
