#!/bin/bash

if [ -e "/etc/pbx/.gmail" ]; then
 echo "Gmail SmartHost is already installed."
 exit 1
fi

clear
echo "This script reconfigures SendMail to use your Gmail account"
echo "as an SMTP SmartHost relay which is required by most providers."
echo "You obviously need a Gmail account to begin."
echo "WARNING... You must use an App Password instead of"
echo "your regular Gmail password below. To obtain an APP password"
echo "go to: https://support.google.com/accounts/answer/185833?hl=en"
echo " "

echo -n "Enter your Gmail account name without @gmail.com: "
read acctname
echo " "
echo -n "Enter your Gmail APP password: "
read acctpw
echo " "
echo "Account name: $acctname"
echo "Account pass: $acctpw"
echo " "
read -p "To proceed, press ENTER or press Ctrl-C to abort."

cd /usr/bin
rm -f makemap
ln -s /usr/sbin/makemap /usr/bin/makemap
cd /etc/mail
hostname -f > genericsdomain
sed -i 's|sendmail-cf|sendmail/cf|' Makefile
rm -f sendmail.mc.gmail
wget http://incrediblepbx.com/sendmail.mc.gmail
#sed -i 's|sendmail-cf|sendmail/cf|' sendmail.mc.gmail
m4 sendmail.mc.gmail > sendmail.cf
chown root /etc/mail
chmod 0755 /etc/mail
touch genericstable
chown smmta:smmsp genericstable
makemap -r hash genericstable.db < genericstable
mkdir -p auth
chmod 700 auth
cd auth
echo AuthInfo:smtp.gmail.com \"U:smmsp\" \"I:user_id\" \"P:password\" \"M:PLAIN\" > client-info
echo AuthInfo:smtp.gmail.com:587 \"U:smmsp\" \"I:user_id\" \"P:password\" \"M:PLAIN\" >> client-info
echo AuthInfo:smtp.gmail.com:465 \"U:smmsp\" \"I:user_id\" \"P:password\" \"M:PLAIN\" >> client-info
sed -i "s|user_id|$acctname|" client-info
sed -i "s|password|$acctpw|" client-info
makemap -r hash client-info.db < client-info
chown root:smmsp client-info.db
cd ..
chown root:smmsp /etc/aliases
newaliases
chown root:smmsp /etc/aliases.db
make
systemctl restart sendmail
systemctl status sendmail
touch /etc/pbx/.gmail
echo "Done."
echo "Now send yourself a test email with the following command:"
echo "echo \"test\" | mail -s testmessage yourname@yourdomain.com"

