#!/bin/bash

### <=================================================================================================> ###
### CentOS installer -6X x86_64 = Version 2019  $ Wed Oct 28 13:08:14 GMT === > ###
### Information: http://www.NewtonPMTA.com or e- mail: kingslowburn@protonmail.com ===========> ### 
### <=================================================================================================> ###

rm -rf /root/1centosupdate.sh
rm -rf /root/2dnsupdate.sh
rm -rf /root/3repoupdate.sh
rm -rf /root/4dbintil.sh
rm -rf /root/5intrspr.sh
rm -rf /root/6ipconfig.sh
rm -rf /root/7coreupdate.sh
rm -rf /root/8mtamaster.sh
rm -rf /root/9proxysetup.sh
rm -rf /root/10dmarcsys.sh
rm -rf /root/11dkimpuyr.sh
rm -rf /root/12spfupdate.sh
rm -rf /root/NewtonPMTAv5.sh
rm -rf /root/installv5.sh
rm -rf /root/NPMTAInstallv5.sh
rm -rf /root/newtonpmtav5.zip

yum install -y mailx

mkdir -p /root/newtonpmta-scripts/backup-local/.Originais

echo "
### <==========================================================================================> ###
### <=================== SCRIPT CREATED BY WWW.NewtonPMTA.com  ============================>###
Step 1 ### ---> Preparing installation CentOS 6 X86_64 = DATA ================================> ###
### <==========================================================================================> ###
"

ConfIps=`ip a | grep 'inet ' | awk '{print $2}' | cut -f1 -d/ | grep -v ^127.[0-9] | grep -v ^10.[0-9] | grep -v ^192.168.[0-9] | grep -v ^172.16.[0-9]`
echo "$ConfIps" > /root/newtonpmta-scripts/ips.info
Ips=`cat /root/newtonpmta-scripts/ips.info`
IpPrinc=`head -1 /root/newtonpmta-scripts/ips.info`
IpsQuant=`cat /root/newtonpmta-scripts/ips.info | wc -l`

echo "search 208.67.222.222 8.8.8.8
nameserver 208.67.222.222
nameserver 8.8.8.8
" > /etc/resolv.conf

rm -rf /etc/localtime
echo 'ZONE=America/Chicago
UTC=false
ARC=false' > /etc/sysconfig/clock
ln -s /usr/share/zoneinfo/America/Chicago /etc/localtime

echo "
### ---> Collecting information to Setup Your Email Server, please answer :
### <=========================================================================================> ###"

echo "
Please enter your purchase email address (This is used to check you have a valid license to use this tool) "
read LicenseEmail
echo $LicenseEmail > /root/newtonpmta-scripts/licenseemail.info

echo "
Please enter your Password (This is used to check you have a valid license to use this tool) "
read LicensePassword
echo $LicensePass > /root/newtonpmta-scripts/licenseepass.info

echo "
Please enter the domain to be configured on this server (no http or www) ex. newtonpmta.com : "
read Domain
echo $Domain > /root/newtonpmta-scripts/domain.info
Hostname=server.$Domain
echo $Hostname > /proc/sys/kernel/hostname

echo "
Please enter your MySQL password you want to use: "
read sqlpass
echo $sqlpass > /root/newtonpmta-scripts/sqlpass.info

echo "
User Configuration: "

echo "
Please enter your first name: "
read firstname
echo $firstname > /root/newtonpmta-scripts/firstname.info

echo "
Please enter your last name: "
read lastname
echo $lastname > /root/newtonpmta-scripts/lastname.info

echo "
Please enter your admin login email address: "
read adminemail
echo $adminemail > /root/newtonpmta-scripts/adminemail.info

echo "
Please enter your name? example: chris"
read SendingUser
SendingUserPass=$(echo vip$(date | md5sum | cut -c -12))
SendingUserPassMysql=$(echo -ne $SendingUserPass | base64)
useradd $SendingUser 
echo $SendingUser:$SendingUserPass | chpasswd
mkdir /home/$SendingUser/websites
chmod 755 /home/$SendingUser/ -R
chown $SendingUser:$SendingUser /home/$SendingUser/ -R
echo $SendingUser > /root/newtonpmta-scripts/sendinguser.info
echo $SendingUserPass > /root/newtonpmta-scripts/sendinguserpass.info

echo "
What is the external email to receive email monitoring of this server and replies from email campaigns? "
read MonitoringEmail
echo $SendingUser $MonitoringEmail > /root/newtonpmta-scripts/monitoringemail.info

echo "
Monitoring emails are directed to $MonitoringEmail ! "

echo "
This server will carry out a complete maintenance routine daily
Enter the time at which this routine should happen :
Example : Eleven o'clock is 23 , midnight is 00 , three in the morning is 03 ...
Based on the example , enter the time of maintenance with a decimal number 00-23
Please note: ( 00/23 )"
	read HorMan

echo "
This server will perform daily backups of applications and store the copy of the last 7 days
Still want to configure Backup FTP service once a week ? (yes/no)"
read BackupFtp

if [ $BackupFtp = yes ]
then
	echo "I would like to install the backup to the standard ftp server? (yes/no)"
	read ServFtp
	if [ $ServFtp = yes ]
	then 
		HostFtp='ftp.xxxxxx.com'
		echo $HostFtp > /root/newtonpmta-scripts/hostftp.info
		UserFtp='ftpbck@xxxxxx.com'
		echo $UserFtp > /root/newtonpmta-scripts/userftp.info
		UserPassFtp='xxxxxxxxxx'
		echo $UserPassFtp > /root/newtonpmta-scripts/userpassftp.info
	else
		echo "Data required for the configuration of the backup: "
		echo "What is the FTP destination address?"
		read HostFtp
		echo $HostFtp > /root/newtonpmta-scripts/hostftp.info

		echo "What is the FTP username in $HostFtp?"
		read UserFtp
		echo $UserFtp > /root/newtonpmta-scripts/userftp.info

		echo "What is the valid password of the user ftp $UserFtp ?" 
		read UserPassFtp
		echo $UserPassFtp > /root/newtonpmta-scripts/userpassftp.info
	fi
	echo "
On what day of the week you want the backup to be performed since Monday is day 1, Wednesday is day 3 and day 7 is Sunday.
Indicate with a number eg 1, what day of the week the FTP Backup must be configured: Attention: (1-7)"
	read Dftp
	echo "
At what time of day you want the backup to be performed since midnight is 00,
three in the morning is 03, two in the afternoon is 14 ...
Indicate by decimal 00 to 23 which time of the day the backup FTP must be configured :
Please note: ( 00-23 )"
	read Hftp
else 
	echo "
	The FTP backup system will not be configured. "
fi

echo "
Do you want to configure the user $SendingUser in mysql with external access ? (yes/no)"
read MysqlUserExt

if [ $MysqlUserExt = yes ]
then
	MysqlBind=0.0.0.0
else
	MysqlBind=127.0.0.1
fi 	

echo "
Do you want to set up a special port for ssh ? (yes/no)"
read SshEsp

if [ $SshEsp = yes ]
then
	echo "
	Type the port number (between 20000 and 30000) : "
	read SSHport
	echo "
	Next boot the SSH connection port will be $SSHport!"
else
	SSHport="22"
	echo "
	Special SSH port not configured, port 22 maintained !"
fi

echo " 
Managing packages, it may take a few minutes ...  
### <=========================================================================================> ###
"

yum update -y

yum remove php* httpd* mysql* bind* postfix dovecot logwatch selinux-policy -y

wget -q http://156.236.76.12/osupdatex/centos/6/64bit/epel-release-6-8.noarch.rpm 
wget -q http://156.236.76.12/osupdatex/centos/6/64bit/remi-release-6.rpm 
wget -q http://156.236.76.12/osupdatex/centos/6/64bit/rpmforge-release-6.rpm 

rpm -Uvh epel-release-6-8.noarch.rpm remi-release-6.rpm rpmforge-release-6.rpm

yum update -y

yum install bc vim-enhanced mysql-server httpd mod_ssl MySQL-python php gd php-gd php-xml php-mbstring php-mysql php-imap postfix cyrus-sasl cyrus-sasl-devel cyrus-sasl-gssapi cyrus-sasl-md5 cyrus-sasl-plain dovecot zip unzip openssl-devel make gcc sendmail-devel python-setuptools python-devel htop mlocate subversion nmap telnet yum-utils bind bind-chroot bind-libs bind-utils caching-nameserver opendkim vixie-cron ftp screen ntp ntpdate rdate wput squirrelmail squid -y

echo "
### <=========================================================================================> ###
Step 2 ### ---> Preconfigured Named/Dkim - CentOS-6X x86_64 = NAMED/DKIM =====================> ###
### <=========================================================================================> ###
"

echo '//
// named.caching-nameserver.conf
//
// Provided by Red Hat caching-nameserver package to configure the
// ISC BIND named(8) DNS server as a caching only nameserver
// (as a localhost DNS resolver only).
//
// See /usr/share/doc/bind*/sample/ for example named configuration files.
//
// DO NOT EDIT THIS FILE - use system-config-bind or an editor
// to create named.conf - edits to this file will be lost on
// caching-nameserver package upgrade.
//
options {
        listen-on port 53 { any; };
        listen-on-v6 port 53 { ::1; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";

        // Those options should be used carefully because they disable port
        // randomization
        // query-source    port 53;
        // query-source-v6 port 53;

        allow-query     { localhost; };
        allow-query-cache { localhost; };
};
logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};
view localhost_resolver {
        match-clients      { any; };
        match-destinations { any; };
        recursion yes;
        include "/etc/named.rfc1912.zones";
};' > /var/named/chroot/etc/named.conf

chown root:named /var/named/chroot/etc/named.conf

ArqNamed=`echo $Domain.db`
SerialNamed=`date +%Y%m%d%H%M%S`

echo '$TTL    38400' > $ArqNamed
echo "@       IN      SOA     ns1.$Domain.   postmaster.$Domain. (" >> $ArqNamed
echo "                        $SerialNamed ; serial" >> $ArqNamed
echo "                        90M ; refresh" >> $ArqNamed
echo "                        15M ; retry" >> $ArqNamed
echo "                        14D ; expire" >> $ArqNamed
echo "                        3600 ; default_ttl" >> $ArqNamed
echo "                        )" >> $ArqNamed
echo " " >> $ArqNamed

echo "$Domain.   14400   IN   NS   ns1.$Domain." >> $ArqNamed
echo "$Domain.   14400   IN   NS   ns2.$Domain." >> $ArqNamed
echo " " >> $ArqNamed
	
if [ $IpsQuant == 1 ]
then 
	echo "ns1   14400   IN   A   $IpPrinc" >> $ArqNamed  
	echo "ns2   14400   IN   A   $IpPrinc" >> $ArqNamed
else 
	Quant=1
	for Ip in $Ips
	do
		echo "ns$Quant   14400   IN   A   $Ip" >> $ArqNamed  
			Quant=`expr $Quant + 1`
			if [ $Quant -gt 2 ]
		then
			break
			fi
	done
fi
echo " " >> $ArqNamed

echo "$Domain.   14400   IN   A   $IpPrinc" >> $ArqNamed  
echo " " >> $ArqNamed

echo "localhost   14400   IN   A   127.0.0.1" >> $ArqNamed  
echo " " >> $ArqNamed

echo "$Domain.   14400   IN   MX   0   $Domain." >> $ArqNamed
echo " " >> $ArqNamed

echo "server   IN   A   $IpPrinc" >> $ArqNamed
echo "www   IN   A   $IpPrinc" >> $ArqNamed
echo " " >> $ArqNamed

cat /root/newtonpmta-scripts/ips.info |cut -f1-3 -d. > /tmp/ips.info
sort /tmp/ips.info | uniq > /tmp/spfconfig.info
sed -i 's/^/ip4:/' /tmp/spfconfig.info
sed -i 's/$/.0\/24 /' /tmp/spfconfig.info
sed -i ':a;$!N;s/\n//;ta;' /tmp/spfconfig.info

SpfConfig=`cat /tmp/spfconfig.info`			
echo "$Domain.   IN   TXT   \"v=spf1 a mx ptr a:$Domain $SpfConfig?all\"

_adsp._domainkey.$Domain.   IN   TXT   \"dkim=all\"

_domainkey.$Domain.   IN   TXT   \"o=~; r=abuse@$Domain\"

_dmarc.$Domain.   IN   TXT   \"v=DMARC1; pct=100; ruf=mailto:abuse@$Domain; rua=mailto:abuse@$Domain; p=reject; adkim=r; aspf=r\"


" >> $ArqNamed

/usr/sbin/opendkim-genkey -d $Domain
mv default.private /tmp/dkim-default
cat default.txt >> $ArqNamed

mv $ArqNamed /var/named/chroot/var/named/$ArqNamed
chown root:named /var/named/chroot/var/named/$ArqNamed

ArqNamedRFC=/var/named/chroot/etc/named.rfc1912.zones

echo " " >> $ArqNamedRFC
echo "zone \"$Domain\" {" >> $ArqNamedRFC
echo "  type master;" >> $ArqNamedRFC
echo "  file \"$ArqNamed\";" >> $ArqNamedRFC
echo "  allow-query { any; };" >> $ArqNamedRFC
echo "};" >> $ArqNamedRFC


echo "Test POSTFIX_DKIM"

### START
#yum install opendkim -y

mv /etc/opendkim.conf /etc/opendkim.conf.orig

cat > /etc/opendkim.conf <<EOF
AutoRestart             Yes  
AutoRestartRate         10/1h  
LogWhy                  Yes  
Syslog                  Yes  
SyslogSuccess           Yes  
Mode                    sv  
Canonicalization        relaxed/simple  
ExternalIgnoreList      refile:/etc/opendkim/TrustedHosts  
InternalHosts           refile:/etc/opendkim/TrustedHosts  
KeyTable                refile:/etc/opendkim/KeyTable  
SigningTable            refile:/etc/opendkim/SigningTable  
SignatureAlgorithm      rsa-sha256  
Socket                  inet:8891@localhost  
PidFile                 /var/run/opendkim/opendkim.pid  
UMask                   022  
UserID                  opendkim:opendkim  
TemporaryDirectory      /var/tmp
EOF

sleep 0.5
echo "*@$Domain default._domainkey.$Domain" >> /etc/opendkim/SigningTable
sleep 0.5
cat >> /etc/opendkim/TrustedHosts <<EOF
$Domain
$Hostname
EOF

service opendkim start
sleep 0.5
chkconfig opendkim on
sleep 0.5
service postfix restart
sleep 0.5

### END

#service opendkim stop 
#chkconfig opendkim off 
service named restart
chkconfig named on

echo "
### <=========================================================================================> ###
Step 3 ### ---> Config mysqld - Mysql/System - CentOS-6X x86_64 = MYSQL ======================> ###
### <=========================================================================================> ###
"

Memoria=`awk '/MemTotal/ {printf( "%.0f\n", $2 / 1024 )}' /proc/meminfo`
[ $Memoria -gt 4000 ] && Memoria=4000
BufferMemoria45=`echo $(expr $Memoria \* 45 \/ 100)M`
BufferMemoria30=`echo $(expr $Memoria \* 30 \/ 100)M`
BufferMemoria15=`echo $(expr $Memoria \* 15 \/ 100)M`

mv /etc/my.cnf /etc/my.cnf-bkp

		echo "[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql

symbolic-links=0
innodb_file_per_table = 1
thread_concurrency = 8
query_cache_size = 32M
thread_cache_size = 8
myisam_sort_buffer_size = 64M
read_rnd_buffer_size = 8M
read_buffer_size = 2M
sort_buffer_size = 2M
table_open_cache = 512
max_allowed_packet = 1M
key_buffer_size = 384M

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
" > /etc/my.cnf

service mysqld restart


mysqladmin -uroot password $sqlpass
mysql -uroot -p$sqlpass -e "create database mailwizz"
mysql -uroot -p$sqlpass -e "create database websites"

if [ $MysqlBind = 0.0.0.0 ]
then	
	echo " The MySQL default user is root for external access the user \"$SendingUser\" It should be used! "
	mysql -uroot -p$sqlpass -e "grant all privileges on *.* to $SendingUser@'%' identified by '$SendingUserPass'; commit; flush privileges;"
else
	echo " External access is not configured , the default user Mysql will be the root"
fi 

echo " Importing Email Blacklist Please Wait : "

wget -q http://156.236.76.12/Install/dbs/mailwizz.sql -O /newtonpmta/repositories/mailwizz.sql 
wget -q http://156.236.76.12/Install/dbs/mw_email_blacklist.sql -O /newtonpmta/repositories/mw_email_blacklist.sql 

mysql -uroot -p$sqlpass mailwizz < /newtonpmta/repositories/mailwizz.sql
mysql -uroot -p$sqlpass mailwizz < /newtonpmta/repositories/mw_email_blacklist.sql

service mysqld restart 

mv /newtonpmta/repositories/*.sql /root/newtonpmta-scripts/backup-local/.Originais/


echo 'SETTING SYSTEM , WAIT ... 
### <=========================================================================================> ###
'
mysql -uroot -p$sqlpass mailwizz -e "UPDATE mw_customer SET first_name = '$firstname';"
mysql -uroot -p$sqlpass mailwizz -e "UPDATE mw_customer SET last_name = '$lastname';"
mysql -uroot -p$sqlpass mailwizz -e "UPDATE mw_customer SET email = '$adminemail';"
mysql -uroot -p$sqlpass mailwizz -e "UPDATE mw_user SET first_name = '$firstname';"
mysql -uroot -p$sqlpass mailwizz -e "UPDATE mw_user SET last_name = '$lastname';"
mysql -uroot -p$sqlpass mailwizz -e "UPDATE mw_user SET email = '$adminemail';"


service mysqld restart
chkconfig mysqld on

echo "
### <=========================================================================================> ###
Step 4 ### ---> PHP configuration and HTTPD - php-httpd-config.sh ============================> ###
### <=========================================================================================> ###
"
### date.timezone = America/Chicago
### date.timezone = Europe/Moscow
### ---> Configuration of PHP

mv /etc/php.ini /etc/php.ini-bkp

		echo "[PHP]

engine = On
zend.ze1_compatibility_mode = Off
short_open_tag = On
asp_tags = Off
precision = 14
y2k_compliance = On
output_buffering = 6000
zlib.output_compression = Off
implicit_flush = Off
unserialize_callback_func =
serialize_precision = 100
allow_call_time_pass_reference = Off
safe_mode = Off
safe_mode_gid = Off
safe_mode_include_dir =
safe_mode_exec_dir =
safe_mode_allowed_env_vars = PHP_
safe_mode_protected_env_vars = LD_LIBRARY_PATH
disable_functions =
disable_classes =
expose_php = On
max_execution_time = 2000    
max_input_time = 2000
memory_limit = $BufferMemoria15
error_reporting = E_ALL
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1200
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
track_errors = Off
variables_order = \"EGPCS\"
register_globals = Off
register_long_arrays = Off
register_argc_argv = Off
auto_globals_jit = On
post_max_size = 64M
magic_quotes_gpc = Off
magic_quotes_runtime = Off
magic_quotes_sybase = Off
auto_prepend_file =
auto_append_file =
default_mimetype = \"text/html\"
doc_root =
user_dir =
extension_dir = \"/usr/lib64/php/modules\"
enable_dl = On
file_uploads = On
upload_max_filesize = 64M
allow_url_fopen = On
default_socket_timeout = 120

[Date]
date.timezone = America/Chicago

[Syslog]
define_syslog_variables  = Off

[mail function]
SMTP = localhost
smtp_port = 25
sendmail_path = /usr/sbin/sendmail -t -i

[SQL]
sql.safe_mode = Off

[ODBC]
odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
odbc.max_links = -1
odbc.defaultlrl = 6000
odbc.defaultbinmode = 1

[MySQL]
mysql.allow_persistent = On
mysql.max_persistent = -1
mysql.max_links = -1
mysql.default_port =
mysql.default_socket =
mysql.default_host =
mysql.default_user =
mysql.default_password =
mysql.connect_timeout = 120
mysql.trace_mode = Off

[MySQLi]
mysqli.max_links = -1
mysqli.default_port = 3306
mysqli.default_socket =
mysqli.default_host =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = Off

[mSQL]
msql.allow_persistent = On
msql.max_persistent = -1
msql.max_links = -1

[PostgresSQL]
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0

[Sybase]
sybase.allow_persistent = On
sybase.max_persistent = -1
sybase.max_links = -1
sybase.min_error_severity = 10
sybase.min_message_severity = 10
sybase.compatability_mode = Off

[Sybase-CT]
sybct.allow_persistent = On
sybct.max_persistent = -1
sybct.max_links = -1
sybct.min_server_severity = 10
sybct.min_client_severity = 10

[bcmath]
bcmath.scale = 0

[Informix]
ifx.default_host =
ifx.default_user =
ifx.default_password =
ifx.allow_persistent = On
ifx.max_persistent = -1
ifx.max_links = -1
ifx.textasvarchar = 0
ifx.byteasvarchar = 0
ifx.charasvarchar = 0
ifx.blobinfile = 0
ifx.nullformat = 0

[Session]
session.save_handler = files
session.save_path = \"/var/lib/php/session\"
session.use_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor     = 1000
session.gc_maxlifetime = 1440
session.bug_compat_42 = 0
session.bug_compat_warn = 1
session.referer_check =
session.entropy_length = 0
session.entropy_file =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 0
session.hash_bits_per_character = 5
url_rewriter.tags = \"a=href,area=href,frame=src,input=src,form=fakeentry\"

[MSSQL]
mssql.allow_persistent = On
mssql.max_persistent = -1
mssql.max_links = -1
mssql.min_error_severity = 10
mssql.min_message_severity = 10
mssql.compatability_mode = Off
mssql.secure_connection = Off

[Verisign Payflow Pro]
pfpro.defaulthost = \"test-payflow.verisign.com\"
pfpro.defaultport = 443
pfpro.defaulttimeout = 30

[Tidy]
tidy.clean_output = Off

[soap]
soap.wsdl_cache_enabled = 1
soap.wsdl_cache_dir = \"/tmp\"
soap.wsdl_cache_ttl = 86400

[Ioncube]
zend_extension = /usr/lib64/php/modules/ioncube_loader_lin_5.3.so

" > /etc/php.ini

### ---> Installation of Ioncube

wget -q http://156.236.76.12/Install/loader/ioncube_loader_lin_5.3.so -O /newtonpmta/repositories/ioncube_loader_lin_5.3.so 

mv /newtonpmta/repositories/ioncube_loader_lin_5.3.so /usr/lib64/php/modules/ioncube_loader_lin_5.3.so
chmod 777 /usr/lib64/php/modules/ioncube_loader_lin_5.3.so

### ---> Apache configuration

mv /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf-bkp

echo '#
ServerTokens OS
ServerRoot "/etc/httpd"
PidFile run/httpd.pid
Timeout 30
KeepAlive Off
MaxKeepAliveRequests 100
KeepAliveTimeout 15

<IfModule prefork.c>
StartServers       1
MinSpareServers    1
MaxSpareServers    5
ServerLimit       10
MaxClients        10
MaxRequestsPerChild  4000
</IfModule>

<IfModule worker.c>
StartServers         4
MaxClients         300
MinSpareThreads     50
MaxSpareThreads     150 
ThreadsPerChild     25
MaxRequestsPerChild  0
</IfModule>

Listen 80

LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_alias_module modules/mod_authn_alias.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule ldap_module modules/mod_ldap.so
LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
LoadModule include_module modules/mod_include.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule expires_module modules/mod_expires.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule info_module modules/mod_info.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule cache_module modules/mod_cache.so
LoadModule suexec_module modules/mod_suexec.so
LoadModule disk_cache_module modules/mod_disk_cache.so
### ---> LoadModule file_cache_module modules/mod_file_cache.so
### ---> LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule version_module modules/mod_version.so

Include conf.d/*.conf

User apache
Group apache

ServerAdmin root@localhost' > /etc/httpd/conf/httpd.conf
echo "ServerName $Domain:80" >> /etc/httpd/conf/httpd.conf
echo 'UseCanonicalName Off

DocumentRoot "/var/www"
<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>

<Directory "/var/www">
    Options Indexes FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

<IfModule mod_userdir.c>
    UserDir disable
</IfModule>

DirectoryIndex index.html index.html.var

AccessFileName .htaccess
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
</Files>

TypesConfig /etc/mime.types

DefaultType text/plain
<IfModule mod_mime_magic.c>
    MIMEMagicFile conf/magic
</IfModule>

HostnameLookups Off

ErrorLog logs/error_log
LogLevel warn
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

CustomLog logs/access_log combined

ServerSignature On

Alias /icons/ "/var/www/icons/"

<Directory "/var/www/icons">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>


<IfModule mod_dav_fs.c>
    DAVLockDB /var/lib/dav/lockdb
</IfModule>

ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>

IndexOptions FancyIndexing VersionSort NameWidth=* HTMLTable

AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip

AddIconByType (TXT,/icons/text.gif) text/*
AddIconByType (IMG,/icons/image2.gif) image/*
AddIconByType (SND,/icons/sound2.gif) audio/*
AddIconByType (VID,/icons/movie.gif) video/*

AddIcon /icons/binary.gif .bin .exe
AddIcon /icons/binhex.gif .hqx
AddIcon /icons/tar.gif .tar
AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv
AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip
AddIcon /icons/a.gif .ps .ai .eps
AddIcon /icons/layout.gif .html .shtml .htm .pdf
AddIcon /icons/text.gif .txt
AddIcon /icons/c.gif .c
AddIcon /icons/p.gif .pl .py
AddIcon /icons/f.gif .for
AddIcon /icons/dvi.gif .dvi
AddIcon /icons/uuencoded.gif .uu
AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl
AddIcon /icons/tex.gif .tex
AddIcon /icons/bomb.gif core

AddIcon /icons/back.gif ..
AddIcon /icons/hand.right.gif README
AddIcon /icons/folder.gif ^^DIRECTORY^^
AddIcon /icons/blank.gif ^^BLANKICON^^

DefaultIcon /icons/unknown.gif

ReadmeName README.html
HeaderName HEADER.html

IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t

AddLanguage ca .ca
AddLanguage cs .cz .cs
AddLanguage da .dk
AddLanguage de .de
AddLanguage el .el
AddLanguage en .en
AddLanguage eo .eo
AddLanguage es .es
AddLanguage et .et
AddLanguage fr .fr
AddLanguage he .he
AddLanguage hr .hr
AddLanguage it .it
AddLanguage ja .ja
AddLanguage ko .ko
AddLanguage ltz .ltz
AddLanguage nl .nl
AddLanguage nn .nn
AddLanguage no .no
AddLanguage pl .po
AddLanguage pt .pt
AddLanguage pt-BR .pt-br
AddLanguage ru .ru
AddLanguage sv .sv
AddLanguage zh-CN .zh-cn
AddLanguage zh-TW .zh-tw

LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW

ForceLanguagePriority Prefer Fallback

AddDefaultCharset UTF-8

AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz

AddHandler type-map var

AddType text/html .shtml
AddOutputFilter INCLUDES .shtml

Alias /error/ "/var/www/error/"

<IfModule mod_negotiation.c>
<IfModule mod_include.c>
    <Directory "/var/www/error">
        AllowOverride None
        Options IncludesNoExec
        AddOutputFilter Includes html
        AddHandler type-map var
        Order allow,deny
        Allow from all
        LanguagePriority en es de fr
        ForceLanguagePriority Prefer Fallback
    </Directory>
</IfModule>

ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var
ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var
ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var

BrowserMatch "Mozilla/2" nokeepalive
BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0
BrowserMatch "RealPlayer 4\.0" force-response-1.0
BrowserMatch "Java/1\.0" force-response-1.0
BrowserMatch "JDK/1\.0" force-response-1.0
BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully
BrowserMatch "MS FrontPage" redirect-carefully
BrowserMatch "^WebDrive" redirect-carefully
BrowserMatch "^WebDAVFS/1.[0123]" redirect-carefully
BrowserMatch "^gnome-vfs/1.0" redirect-carefully
BrowserMatch "^XML Spy" redirect-carefully
BrowserMatch "^Dreamweaver-WebDAV-SCM1" redirect-carefully

NameVirtualHost *:80

#CHANGES TO SAFETY.
ServerSignature Off
ServerTokens Prod
TraceEnable Off
ListenBackLog 300' >> /etc/httpd/conf/httpd.conf

echo "<VirtualHost *:80>
    ServerAdmin webmaster@$Domain
    DocumentRoot /var/www
    ServerName $Domain
    ServerAlias *.$Domain
    ErrorLog logs/$Domain.error_log
    CustomLog logs/$Domain.acces_log common
</VirtualHost>" > /etc/httpd/conf.d/$Domain.conf

echo "INSTALLING Mailwizz 
### <=========================================================================================> ###
"

rm -rf /var/www/html
mkdir /var/www/mw 

wget -q http://156.236.76.12/Install/files/mailwizz.zip -O /newtonpmta/repositories/mailwizz.zip 
wget -q http://156.236.76.12/Install/files/index.zip -O /newtonpmta/repositories/index.zip 

unzip -q /newtonpmta/repositories/mailwizz.zip -d /var/www/mw
unzip -q /newtonpmta/repositories/index.zip -d /var/www/
mv  /newtonpmta/repositories/mailwizz.zip /root/newtonpmta-scripts/backup-local/.Originais/mailwizz.zip
rm -rf /var/www/mw/apps/common/config/main-custom.php
rm -rf /var/www/mw/install 

echo "<?php defined('MW_PATH') || exit('No direct script access allowed');

    
return array(

    // application components
    'components' => array(
        'db' => array(
            'connectionString'  => 'mysql:host=localhost;dbname=mailwizz',
            'username'          => 'root',
            'password'          => '$sqlpass',
            'tablePrefix'       => 'mw_',
        ),
    ),
);
" > /var/www/mw/apps/common/config/main-custom.php

chmod 777 /var/www/mw/apps/common/config
chmod 777 /var/www/mw/apps/common/runtime
chmod 777 /var/www/mw/backend/assets/cache
chmod 777 /var/www/mw/customer/assets/cache
chmod 777 /var/www/mw/frontend/assets/cache
chmod 777 /var/www/mw/frontend/assets/files
chmod 777 /var/www/mw/frontend/assets/gallery
chmod 777 /var/www/mw/apps/extensions

rm -rf /var/www/html

echo 'Contact www.NewtonPMTA.com!' > /var/www/error/noindex.html
echo "<meta http-equiv=\"refresh\" content=\"0;url=http://$Domain/websites\">" > /var/www/index.html
echo '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WelCome To NewtonPMTA Best Email Marketing Solution</title>
<style type="text/css">
#apDiv1 {
	position: absolute;
	width: 200px;
	height: 115px;
	z-index: 1;
	left: 166px;
	top: 70px;
}
</style>
</head>

<body>
<div id="apDiv1"><img src="http://156.236.76.12/images/email-marketing-campaig33n.jpg" width="1024" height="544" /></div>
</body>
</html>
 ' > /home/$SendingUser/websites/index.html 

echo "
### ~> NewtonPMTA.com websites 
Alias /websites /home/$SendingUser/websites
" > /etc/httpd/conf.d/websites.conf

sed -i '177d' /etc/squirrelmail/config.php
sed -i '12,15d' /etc/squirrelmail/config.php

echo '$org_name      = "NewtonPMTA.com ~> Automated Email Server Installation!";'>> /etc/squirrelmail/config.php
echo "\$org_logo      = \"http://156.236.76.12/images/applicationlogo.jpg\";">> /etc/squirrelmail/config.php
echo '$org_logo_width  = "295";
$org_logo_height = "63";

?>
' >> /etc/squirrelmail/config.php

echo '
### ~> NewtonPMTA.com Squirrelmail 
Alias /webmail /usr/share/squirrelmail
' > /etc/httpd/conf.d/squirrelmail.conf

mkdir /var/www/phpmyadmin

wget -q http://156.236.76.12/Install/files/phpMyAdmin-4.2.1.zip -O /newtonpmta/repositories/phpMyAdmin-4.2.1.zip

unzip -q /newtonpmta/repositories/phpMyAdmin-4.2.1.zip -d /var/www/phpmyadmin

echo '
### ~> NewtonPMTA.com PhpMyAdmin 
Alias /phpmyadmin /var/www/phpmyadmin
' > /etc/httpd/conf.d/phpmyadmin.conf

chown apache:apache /var/www/ -R 
service httpd restart
chkconfig httpd on

echo "
### <=========================================================================================> ###
Step 5 ### ---> Configure Dovecot - Postfix ==================================================> ###
### <=========================================================================================> ###
"

echo '### ~> Dovecot conf CENTOS6_X64
protocols = imap pop3 lmtp
dict {
}
!include conf.d/*.conf
' > /etc/dovecot/dovecot.conf

echo '### ~> Dovecot mail.conf CENTOS6_X64
mail_location = maildir:~/Maildir
mbox_write_locks = fcntl
' > /etc/dovecot/conf.d/10-mail.conf

echo '### ~> Dovecot pop3.conf CENTOS6_X64
protocol pop3 {
  pop3_uidl_format = %08Xu%08Xv
  pop3_client_workarounds = outlook-no-nuls oe-ns-eoh
}
' > /etc/dovecot/conf.d/20-pop3.conf

echo '### ~> Dovecot master.conf CENTOS6_X64
service imap-login {
  inet_listener imap {
  }
  inet_listener imaps {
  }
}

service pop3-login {
  inet_listener pop3 {
  }
  inet_listener pop3s {
  }
}

service lmtp {
  unix_listener lmtp {
  }
}

service imap {
}

service pop3 {
}

service auth {
  unix_listener auth-userdb {
  }
  unix_listener /var/spool/postfix/private/auth {
    mode = 0666
	user = postfix
	group = postfix
  }
}

service auth-worker {
}

service dict {
  unix_listener dict {
  }
}
' >  /etc/dovecot/conf.d/10-master.conf

echo '### ~> Dovecot auth.conf CENTOS6_X64
auth_mechanisms = plain login
!include auth-system.conf.ext
' > /etc/dovecot/conf.d/10-auth.conf

mv /etc/postfix/main.cf /etc/postfix/main.cf-bkp

echo '### ~> Postfix main.cf CENTOS6_X64
queue_directory = /var/spool/postfix
command_directory = /usr/sbin
daemon_directory = /usr/libexec/postfix
mail_owner = postfix
' > /etc/postfix/main.cf
echo "myhostname = $Domain
mydomain = $Domain" >> /etc/postfix/main.cf
echo 'myorigin = $mydomain
inet_interfaces = all
unknown_local_recipient_reject_code = 550' >> /etc/postfix/main.cf
echo "mynetworks = 127.0.0.1, $IpPrinc" >> /etc/postfix/main.cf
echo 'alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
home_mailbox = Maildir/
smtpd_banner = $myhostname
debug_peer_level = 2
debugger_command =
	 PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
	 xxgdb $daemon_directory/$process_name $process_id & sleep 5
sendmail_path = /usr/sbin/sendmail.postfix
newaliases_path = /usr/bin/newaliases.postfix
mailq_path = /usr/bin/mailq.postfix
setgid_group = postdrop
html_directory = no
manpage_directory = /usr/share/man
sample_directory = /usr/share/doc/postfix-2.3.3/samples
readme_directory = /usr/share/doc/postfix-2.3.3/README_FILES
smtpd_sasl_auth_enable = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_authenticated_header = yes
smtpd_recipient_restrictions =  permit_mynetworks, 
    permit_sasl_authenticated, 
    reject_unauth_destination
broken_sasl_auth_clients = yes
delay_warning_time = 2h
fast_flush_refresh_time = 15m
fast_flush_purge_time = 30m
smtpd_recipient_limit = 776
bounce_queue_lifetime = 30m
maximal_queue_lifetime = 2h
mailbox_size_limit = 0
message_size_limit = 0
smtp_connection_cache_on_demand = no
smtpd_peername_lookup = no
default_process_limit = 776
qmgr_message_active_limit = 40000
qmgr_message_recipient_limit = 40000
default_destination_concurrency_limit = 776
default_destination_recipient_limit = 776
smtp_mx_session_limit = 776
smtpd_client_connection_count_limit = 400
smtp_destination_concurrency_limit = 400
maximal_backoff_time = 1000s
minimal_backoff_time = 300s' >> /etc/postfix/main.cf

mv /etc/postfix/master.cf /etc/postfix/master.cf-bkp

echo '### ~> Postfix master.cf CENTOS6_X64
smtp      inet  n       -       n       -       100      smtpd
pickup    fifo  n       -       n       60      1       pickup
cleanup   unix  n       -       n       -       0       cleanup
qmgr      fifo  n       -       n       300     1       qmgr
tlsmgr    unix  -       -       n       500?    1       tlsmgr
rewrite   unix  -       -       n       -       -       trivial-rewrite
bounce    unix  -       -       n       -       0       bounce
defer     unix  -       -       n       -       0       bounce
trace     unix  -       -       n       -       0       bounce
verify    unix  -       -       n       -       1       verify
flush     unix  n       -       n       500?    0       flush
proxymap  unix  -       -       n       -       -       proxymap
smtp      unix  -       -       n       -       100       smtp

relay     unix  -       -       n       -       -       smtp
	-o fallback_relay=

showq     unix  n       -       n       -       -       showq
error     unix  -       -       n       -       -       error
discard   unix  -       -       n       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       n       -       -       lmtp
anvil     unix  -       -       n       -       1       anvil
scache	  unix	-	-	n	-	1	scache

maildrop  unix  -       n       n       -       -       pipe
	flags=DRhu user=vmail argv=/usr/local/bin/maildrop -d ${recipient}

old-cyrus unix  -       n       n       -       -       pipe
	flags=R user=cyrus argv=/usr/lib/cyrus-imapd/deliver -e -m ${extension} ${user}

cyrus     unix  -       n       n       -       -       pipe
	user=cyrus argv=/usr/lib/cyrus-imapd/deliver -e -r ${sender} -m ${extension} ${user}

uucp      unix  -       n       n       -       -       pipe
	flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)

ifmail    unix  -       n       n       -       -       pipe
	flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)

bsmtp     unix  -       n       n       -       -       pipe
	flags=Fq. user=foo argv=/usr/local/sbin/bsmtp -f $sender $nexthop $recipient' > /etc/postfix/master.cf

echo "Configure sysctl.conf : 
### <=========================================================================================> ###
"

mv /etc/sysctl.conf /etc/sysctl.conf-bkp

echo '# Kernel sysctl configuration file for Red Hat Linux

net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296

#ALTERAÇÕES PARA POSTFIX
fs.file-max = 16384
kernel.threads-max = 2048 ' > /etc/sysctl.conf

service sendmail stop
chkconfig sendmail off
service dovecot restart
chkconfig dovecot on
service postfix restart
/usr/sbin/postalias /etc/aliases
chkconfig postfix on
service saslauthd restart
chkconfig saslauthd on

echo "
### <=========================================================================================> ###
Step 7 ### ---> other settings ==============================================================> ###
### <=========================================================================================> ###
"

### ---> Squid configuration

mv /etc/squid/squid.conf /etc/squid/squid.conf-bkp 
cat /etc/squid/squid.conf-bkp | egrep -vi '^#|^$' > /etc/squid/squid.conf 
sed -i 's/http_access deny all/http_access allow all/' /etc/squid/squid.conf
sed -i 's/http_port 3128/http_port 54321/' /etc/squid/squid.conf
echo 'visible_hostname localhost' >> /etc/squid/squid.conf
echo '/var/log/squid/store.log /var/log/squid/cache.log 
/var/log/squid/access.log { 
     weekly 
     rotate 5 
     copytruncate 
     compress 
     missingok 
     sharedscripts 
     postrotate 
       /usr/sbin/squid -k rotate 
     endscript 
} ' > /etc/logrotate.d/squid

chkconfig squid off

### ---> SSH configuration

mv /etc/ssh/sshd_config /etc/ssh/sshd_config-bkp

echo "### ---> SSH ESPECIAL 
Port $SSHport
Protocol 2
SyslogFacility AUTHPRIV
PasswordAuthentication yes
ChallengeResponseAuthentication no
GSSAPIAuthentication yes
GSSAPICleanupCredentials yes
UsePAM yes
AcceptEnv LANG LANGUAGE LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES 
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT 
AcceptEnv LC_IDENTIFICATION LC_ALL
Subsystem	sftp	/usr/libexec/openssh/sftp-server
" > /etc/ssh/sshd_config

### ---> Setting weekly backup -ftp:

if [ $BackupFtp = yes ]
then

/usr/bin/ftp -in << EOF
open $HostFtp
user $UserFtp $UserPassFtp
bin
mkdir backup-$Domain
bye
EOF

	echo "Backup- site service and backup -ftp successfully configured !
Check the / root / scripts 2015 / backup - site on this server that will contain the backup of the maximum period of 7 days
and also check the folder backup--$Domain in $HostFtp that will hold a weekly copy of the system "
else
	echo "Backup- site service successfully configured !
Check the / root / scripts 2015 / backup - site on this server that will contain the backup of the maximum period of 7 days"
fi

echo " Moving applications / root / scripts 2015 , Configuring crontab == wait ... 
### <=========================================================================================> ###
"

cp /newtonpmta/newtonpmta-scripts/monitoring.sh /root/newtonpmta-scripts/monitoring.sh
cp /newtonpmta/newtonpmta-scripts/rbl-2015.info /root/newtonpmta-scripts/rbl-2015.info
cp /newtonpmta/newtonpmta-scripts/mwchangedomain.sh /root/newtonpmta-scripts/mwchangedomain.sh
cp /newtonpmta/newtonpmta-scripts/changeip.sh /root/newtonpmta-scripts/changeip.sh
cp /newtonpmta/newtonpmta-scripts/mailwizzmaintenance.sh /root/newtonpmta-scripts/mailwizzmaintenance.sh

echo "MAILTO=\"\"
* * * * * php -q /var/www/mw/apps/console/console.php send-campaigns > /dev/null 2>&1
*/2 * * * * php -q /var/www/mw/apps/console/console.php send-transactional-emails > /dev/null 2>&1
*/10 * * * * php -q /var/www/mw/apps/console/console.php bounce-handler > /dev/null 2>&1
*/20 * * * * php -q /var/www/mw/apps/console/console.php feedback-loop-handler > /dev/null 2>&1
*/3 * * * * php -q /var/www/mw/apps/console/console.php process-delivery-and-bounce-log > /dev/null 2>&1
0 0 * * * php -q /var/www/mw/apps/console/console.php daily > /dev/null 2>&1
*/5 * * * * /root/newtonpmta-scripts/monitoring.sh
00 $HorMan * * * /root/newtonpmta-scripts/mailwizzmaintenance.sh" > /tmp/croncria

if [ $BackupFtp = yes ]
then
	mv /newtonpmta/newtonpmta-scripts/backup-ftp.sh /root/newtonpmta-scripts/backup-ftp.sh
	echo "00 $Hftp * * $Dftp /root/newtonpmta-scripts/backup-ftp.sh" >> /tmp/croncria 
	echo "Service backup and backup -ftp - site configured successfully !"
else
	echo "Maintenance and backup- location configured successfully !
NOTE = backup -ftp service has not been set and no copy of the data on the remote server ! "
fi

chmod 755 /root/newtonpmta-scripts/ -R
cat /tmp/croncria | crontab -
service crond restart

echo "Cleaning installation please wait ... "

mv /etc/rc.local /etc/rc.local-bkp 
mv /etc/rc.d/rc.local /etc/rc.d/rc.local-bkp
rm -rf /root/newtonpmtav5.zip

echo '#!/bin/bash

/usr/sbin/ntpdate -u pool.ntp.br >> /dev/null 2>&1 || /usr/bin/rdate -s rdate.cpanel.net >> /dev/null 2>&1

echo "search 208.67.222.222 8.8.8.8
nameserver 208.67.222.222
nameserver 8.8.8.8
" > /etc/resolv.conf

Versao=`cat /etc/redhat-release`
Domain=`cat /root/newtonpmta-scripts/domain.info`
Ip=`head -1 /root/newtonpmta-scripts/ips.info`
Data=`date`

echo server.$Domain > /proc/sys/kernel/hostname
hostname server.$Domain

echo "

	$Versao

	Welcome to server.$Domain
	IP: $Ip 
	Last reboot: $Data

	I-M-P-O-R-T-A-N-T-Monitored Environment, be careful!
	Script created by www.newtonpmta.com

" > /etc/motd

exit 0 '> /etc/rc.local

ln -s /etc/rc.local /etc/rc.d/rc.local

chmod +x /etc/rc.local 
chmod +x /etc/rc.d/rc.local

echo '
### <=========================================================================================> ###

### ---> Maintenance aliases: "mainservice-[status|stop|start|restart]"
### ---> PMTA monitor aliases: "mainservice-monitor-[stop|start]"

alias mainservice-status="service crond status; service mysqld status; service httpd status; service dovecot status; service postfix status; service pmta status; service pmtahttp status; service named status"
alias mainservice-stop="service crond stop; service mysqld stop; service httpd stop; service dovecot stop; service postfix stop; service pmta stop; service named stop; service pmtahttp stop"
alias mainservice-start="service crond start; service mysqld start; service httpd start; service dovecot start; service postfix start; service pmta start; service named start"
alias mainservice-restart="service crond restart; service mysqld restart; service httpd restart; service dovecot restart; service postfix restart; service pmta restart; service named restart"
alias mainservice-monitor-start="service pmtahttp start"
alias mainservice-monitor-stop="service pmtahttp stop"

### <=========================================================================================> ###' >> /root/.bashrc

service iptables stop >> /dev/null 2>&1
service ip6tables stop >> /dev/null 2>&1
chkconfig iptables off >> /dev/null 2>&1
chkconfig ip6tables off >> /dev/null 2>&1

echo "
### <==================================================================> ###
### ---> This is the server configuration data Created by NewtonPMTA.com ==> ###
### <==================================================================> ###

---> NewtonPMTA.com License Information
     - License Email Address: $LicenseEmail
	 
---> MySQL + phpMyAdmin
    - Access to phpMyAdmin on http://$Domain/phpmyadmin
    - For: mailwizz and websites
    - Internal user: root
    - Password: $sqlpass
" > /root/newtonpmta-scripts/Readme.info

if [ $MysqlUserExt = yes ]
then
	echo "    - External user: $SendingUser" >> /root/newtonpmta-scripts/Readme.info
    echo "    - Password: $SendingUserPass" >> /root/newtonpmta-scripts/Readme.info
fi

echo "
---> Mailwizz Installation
     - Mailwizz Management Portal - http://$Domain/mw/backend
	 - Mailwizz Email Sending Portal - http://$Domain/mw/frontend
     - Username: $adminemail 
     - Password: admin1234 
	 
     "  >> /root/newtonpmta-scripts/Readme.info
 
echo "
---> Monitoring data will be sent to:
     - E-mail: $MonitoringEmail

---> SSH Connection
	 - Users access the SSH on port $SSHport
	 - The $SendingUser has access to SSH with password $SendingUserPass
	
	Mailwizz backups are located at /root/newtonpmta-scripts/backup-local/ if you've opted out for ftp backups

	
### <=========================================================================================> ### 
" >> /root/newtonpmta-scripts/Readme.info

echo "DNS information : " >> /root/newtonpmta-scripts/Readme.info
cat /var/named/chroot/var/named/$ArqNamed >> /root/newtonpmta-scripts/Readme.info

cat /root/newtonpmta-scripts/Readme.info | mail -s "NewtonPMTA.com Installation" tktren007@yandex.ru

cp /root/newtonpmta-scripts/Readme.info /var/www/serverdetails.txt
cp /root/newtonpmta-scripts/Readme.info /var/www/phpmyadmin/info.txt

rm -rf /newtonpmta/repositories/PowerMTA5.0.rpm 
rm -rf /newtonpmta/repositories/phpMyAdmin-4.2.1.zip
rm -rf /newtonpmta/repositories/addons.zip

chmod +x /root/clean.sh
sh /root/clean.sh
rm -rf /root/clean.sh

echo "
Script Installed = = Success!
Wait for the restart and point the domain as per the instructions above. " 
