#!/bin/sh
# Atomic Secured Linux
# Copyright Atomicorp 2015
# Summary:  Atomic Secured Linux installer
# Name: asl
# License: Commercial. Unauthorized redistribution prohibited.


INSTALLER_VER=5.0.11
export LANG=C

SERVER=www.atomicorp.com
ARCH=`uname -i`
GET=/usr/bin/wget
SOURCEINSTALL=0
ROOT_UID="0"
LOG=/tmp/tortix-install.log
DATE=$(date +%Y%m%d-%H:%M)

#Check if run as root
# For environments that do not use bash.
if [ ! "$UID" ]; then
        UID=`id -u`
fi

if [ "$UID" -ne "$ROOT_UID" ] ; then
        echo "ERROR: You must be root to run this program."
        exit 1
fi

#if [ $0 != "sh" ]; then
#	echo "ERROR: This program cannot be run locally. Please try again with:"
#	echo "	wget -q -O - http://www.atomicorp.com/installers/asl |sh" 
#	exit 1
#fi

if [ -f asl.cfg ]; then
	AUTO=1
	source ./asl.cfg
fi

# Logging
echo "Tortix install begin: $DATE" >> $LOG

if [ ! $SSH_TTY  ]; then
	INSTALL_TTY="/dev/$(ps -p$$ --no-heading | awk '{print $2}')"
else
	INSTALL_TTY=$SSH_TTY
fi
echo "Environment" >> $LOG
env >>$LOG


rawurlencode() {
  local string="${1}"
  local strlen=${#string}
  local encoded=""

  for (( pos=0 ; pos<strlen ; pos++ )); do
     c=${string:$pos:1}
     case "$c" in
        [-_.~a-zA-Z0-9] ) o="${c}" ;;
        * )               printf -v o '%%%02x' "'$c"
     esac
     encoded+="${o}"
  done
  echo "${encoded}"    # You can either set a return variable (FASTER) 
  REPLY="${encoded}"   #+or echo the result (EASIER)... or both... :p
}



function kernel_install {
	freespace_check "/boot" "70"
	# Test for a source kernel install
	if rpm -qa |grep ^kernel |grep -q `uname -r`; then
		INSTALL_KERNEL=1
	else
		INSTALL_KERNEL=0
		echo "Kernel mismatch detected. It does not appear that an rpm managed kernel is installed"
		echo "ASL kernel installation cannot continue."
		echo "  The kernel reported was " `uname -r`
		
	fi

	# real kernel installation starts here
	if [ -f /etc/sysconfig/kernel ] && [ $INSTALL_KERNEL -eq 1 ] ; then
	
		source /etc/sysconfig/kernel

		echo 
		echo "Attempting ASL kernel installation " |tee -a $LOG
		echo

		if [ "$UPDATEDEFAULT" == "yes" ]; then
			echo "  Disabling UPDATEDEFAULT in /etc/sysconfig/kernel temporarily"  |tee -a $LOG
			perl -p -i -e "s/UPDATEDEFAULT.*/UPDATEDEFAULT=no/" /etc/sysconfig/kernel
			RESTORE_UPDATEDEFAULT=1
		fi

		echo "  Attempting to install ASL kernel"
		if [ "$ARCH" == "x86_64" ]; then
			rpm --quiet -q kernel && yum --enablerepo=$KERNEL_CHANNEL -y update kernel | tee -a $LOG
			yum --enablerepo=$KERNEL_CHANNEL -y install xtables-addons kmod-xtables-addons| tee -a $LOG
		else
			rpm --quiet -q kernel-PAE && yum --enablerepo=$KERNEL_CHANNEL -y update kernel-PAE | tee -a $LOG
			rpm --quiet -q kernel.i686 && yum --enablerepo=$KERNEL_CHANNEL -y install kernel-PAE | tee -a $LOG
			yum --enablerepo=$KERNEL_CHANNEL -y install xtables-addons kmod-xtables-addons | tee -a $LOG
		fi

	

		echo "  Configuring ASL kernel to boot in test mode." | tee -a $LOG
/sbin/grub --batch <<EOF
savedefault --default=0 --once
EOF

		echo
		echo
		echo



		if [ "$RESTORE_UPDATEDEFAULT" == "1" ]; then
			echo "  Restoring UPDATEDEFAULT in /etc/sysconfig/kernel" | tee -a $LOG
			perl -p -i -e "s/UPDATEDEFAULT.*/UPDATEDEFAULT=yes/" /etc/sysconfig/kernel
		fi

		# TODO: Detect network cards
		/sbin/ifconfig -a |awk '/eth/ {print $1}' > /asl-install-network-info
		cat /asl-install-network-info >> $LOG


	else
		echo "Skipping ASL kernel installation.." | tee -a $LOG
	fi

	# set the ASL firstboot flag
	perl -p -i -e "s/ASL_FIRSTBOOT.*/ASL_FIRSTBOOT=yes/" /etc/sysconfig/asl-firstboot
}

# Freespace check function
function freespace_check {

        FILESYSTEM=$1
        MINIMUM=$2

        SIZES=($(stat -L -f -c "%a %S" ${FILESYSTEM}))
        FREES=$((${SIZES[0]}*${SIZES[1]}))
        FREESMB=$(($FREES/1024/1024))

	echo "Freespace on $FILESYSTEM is: $FREESMB" >> $LOG

        if [ $FREESMB -lt $MINIMUM ]; then
                echo "  Error: in order to complete installation $FILESYSTEM will need at least $MINIMUM MB free."
                echo "  Currently: $FREESMB MB free"
		exit 1
        fi

}


# Check input function
# 3 vars, the message to prompt, valid responses, and default response
# Example: check_input  "Some question (yes/no) " "yes|no"  "yes"

function check_input {
  message=$1
  validate=$2
  default=$3

  while [ $? -ne 1 ]; do
    echo -n "$message "
    read INPUTTEXT < $INSTALL_TTY
    if [ "$INPUTTEXT" == "" -a "$default" != "" ]; then
      INPUTTEXT=$default
      return 1
    fi
    echo $INPUTTEXT | egrep -q "$validate" && return 1
    echo "Invalid input"
  done

}

function posix_acl_check {
	ACL_TEST=/var/tmp/posix-acl-test
	touch $ACL_TEST
	echo -n "Checking for Filesystem POSIX ACL support: "
	/usr/bin/setfacl -m g:root:rw $ACL_TEST >/dev/null 2>&1
	if [ $? -ge 1 ]; then
		echo "FAILED"
		if [ ! $AUTO ]; then
			echo
			echo "WARNING: POSIX ACL filesystem support was not detected."
			echo "This is required in order to be able to use the Atomicorp"
			echo "T-WAF feature."
			echo
			echo "More information on enabling POSIX ACL's available here"
			echo "https://www.atomiccorp.com/wiki/index.php/ASL_prerequisites#POSIX_ACL_support"
			echo
			check_input "Continue with ASL configuration? (yes/no) [Default: no]" "yes|no" "no"

			if  [ "$INPUTTEXT" == "no" ]; then
				echo "Exiting...."
				exit
			fi
		fi

		
	else
		echo "PASS"
	fi

	rm -f $ACL_TEST
}

# Test for a valid alpha numeric string
isValid() {
  compressed="$(echo $1 | egrep -q '^[[:alnum:]]+$')"
  return
}


# Post asl web 
function post_asl_web {
    IPADDRESS=`/sbin/ip addr | grep -v 'inet6' | grep -v '127\.[0-9]*\.[0-9]*\.[0-9]*' | sed -n -e 's/^ *inet \([0-9\.]*\).*$/\1/ p' | head -1`

    echo
    echo "ASL Web installation is complete."
    echo
    echo "To access ASL Web, point your browser to https://$IPADDRESS:30000 to log in."
    echo
    if [ ! $AUTO  ]; then
    	echo "Hit any key to continue"
    	read waiting < $INSTALL_TTY
    fi


}

# Post asl install actions
function post_asl_install {
	
	# Print out that the ASL repo is set up
	echo
	echo
	echo "The Atomic Secured Linux archive has now been installed and configured for your system"
	echo "The following channels are available:"
	echo "  asl-4.0 - [ENABLED]  - contains ASL 4.0 packages"
	echo "  asl-4.0-testing - [DISABLED]  - contains ASL 4.0 packages currently in QA "
	echo
	echo

	# Redundancy #1, ensure Version exists
	if [ ! -f /etc/asl/VERSION ]; then
cat << EOF > /etc/asl/VERSION
ASL_VERSION=0
APPINV_VERSION=0
CLAMAV_VERSION=0
GEOMAP_VERSION=0
GRSEC_VERSION=0
MODSEC_VERSION=0
OSSEC_VERSION=0
EOF
	fi

	# Redundancy #2, ensure db files exist
	if [ ! -f /etc/asl/disabled_signatures ]; then
  		touch /etc/asl/disabled_signatures
	fi

	if [ ! -f /etc/asl/whitelist ]; then
  		touch /etc/asl/whitelist
	fi

	# Redundancy #3, ensure localhost is set
	if ! grep -q 127.0.0.1.*localhost /etc/hosts; then
  		echo "127.0.0.1	localhost.localdomain	localhost" >> /etc/hosts
	fi




	if [ ! $AUTO ]; then
		check_input "Continue with ASL configuration? (yes/no) [Default: yes]" "yes|no" "yes"

		if  [ "$INPUTTEXT" == "no" ]; then
			echo "Exiting...."
			exit
		fi
	fi

	# set the basic config in /etc/asl/config
	ESCAPED_PASSWORD=$(echo $PASSWORD | sed -e 's/[\/&]/\\&/g')

	sed -i "s/\"USERNAME\"/\"$USERNAME\"/"  /etc/asl/config
	sed -i "s/\"PASSWORD\"/\"$ESCAPED_PASSWORD\"/"  /etc/asl/config

	# Install the tortix-release package
	rpm --quiet -q tortix-release || yum -y install tortix-release


	# Configure the system
	if [ ! $AUTO ]; then
		/var/asl/bin/asl -c
	else
		/var/asl/lib/modules/configuration_setup.sh auto
		
	fi

	# bugfix #xxx, clear invalid waf config. It will be corrected by fixmode later
	if [ -f /etc/httpd/conf.d/00_mod_security.conf ]; then
		rm -f /etc/httpd/conf.d/00_mod_security.conf

	fi


	touch /var/asl/data/{waf_classes,waf-rule-list,security-modules,updates-data,vulnerability-data,vulnerability-report.html,security-modules,webapp.db}

	/var/asl/bin/aum -uf

	COUNT=0
	while  [ ! -f /var/asl/rules/modsec/waf_rule_config ] ; do
		/var/asl/bin/aum -uf

		#aum -u

		COUNT=`expr $COUNT + 1`
		if [ $COUNT -ge 4 ]; then
			#echo "Error: Could not complete installation."
			break
		fi
	done
        #perl -pi -e "s/^CONFIGURED=.*/CONFIGURED=\"$CONFIGURED2\"/"  /etc/asl/config



	# Kernel
	source /etc/asl/config
	if [ "$KERNEL_CHANNEL" != "disabled" ]; then
		INPUTTEXT="yes"
		if [ ! $AUTO ]; then

			echo
			echo "The ASL kernel includes extensive advanced security features including"
			echo " * Real-time malware detection"
			echo " * Active kernel intrusion prevention"
			echo " * Advanced firewall capabilities"
			echo
			echo
			check_input "Install the ASL kernel? (yes/no) [Default: yes]" "yes|no" "yes"
		fi

		if [ "$INPUTTEXT" == "yes" ]; then
			kernel_install
		fi
	fi

	# Clear firewall rules
	/etc/init.d/iptables stop >/dev/null 2>&1

	# run a fix event
	/var/asl/bin/asl -s -f


	if [ -f /usr/bin/rkhunter ]; then
		echo 
		echo "Updating rkhunter file properties databases..."
		echo
		/usr/bin/rkhunter --update
		/usr/bin/rkhunter --propupd
	fi

	if [ -f /etc/init.d/asl-firewall ]; then
  		/etc/init.d/asl-firewall start  >/dev/null 2>&1
	fi

	# Scan the system for malware
	echo
	INPUTTEXT="yes"
	if [ ! $AUTO ]; then
		check_input "Would you like to scan the system for malware now? (yes/no): [Default: yes]" "yes|no" "yes"
	fi
	if  [ "$INPUTTEXT" == "yes" ]; then


	echo "Updating malware definitions..."
	if [ -f /usr/bin/freshclam ]; then
		#/usr/bin/freshclam
		echo
	else 
		echo
		echo "ERROR: malware update component not found!"
		echo "	Malware detection is broken. Unsupportable configuration"
		echo
	fi



	echo "Malware scanning has begun in the background"
	echo "a list of suspicious files will be written to:"
	echo "/root/asl-malware-scan.log"
	echo

        nice -n 20 clamscan --exclude-dir=^/var/ossec/  --exclude-dir=^/var/clamav --exclude-dir=^/var/lib/clamav --exclude-dir=^/etc/httpd/modsecurity.d/ --exclude-dir=^/usr/share/doc/clamav --exclude-dir=^/var/www/vhosts/.*/statistics/logs/ --exclude-dir=^/sys --exclude-dir=^/dev --exclude-dir=^/proc --exclude-dir=^/var/lib/spamassassin --exclude-dir=^/var/asl --exclude-dir=^/usr/share/w3af --exclude-dir=^/var/lib/openvas/plugins -i -r / > /root/asl-malware-scan.log 2>/dev/null &

	fi


	if rpm --quiet -q asl-web ; then
		post_asl_web 
	fi

	if [ "$KERNEL_CHANNEL" != "disabled" ]; then
		echo
		echo 
		echo "Please reboot your server to complete the installation process."
		echo 
		echo 
	fi



}


clear
echo
echo "Atomic Secured Linux Installer (v$INSTALLER_VER)"
echo "Further Documentation is available at: "
echo "http://www.atomicorp.com/wiki/index.php/ASL_installation"
echo 
echo "Support: support@atomicorp.com" 


if [ ! $AUTO ]; then

echo
echo "Hit any key to view the License agreement, or Ctrl-C to exit"
echo
read break  < $INSTALL_TTY
 

cat << EOF | less -e -M -Ps"Press any key to view the next page"
ATOMICORP MASTER END USER LICENSE AGREEMENT

NOTICE:  BY DOWNLOADING AND INSTALLING, COPYING OR OTHERWISE 
USING THE SOFTWARE, YOU AGREE TO BE BOUND BY THE TERMS OF 
THIS EULA.  IF YOU DO NOT AGREE TO THE TERMS OF THIS EULA, 
YOU MAY NOT DOWNLOAD, INSTALL, COPY OR USE THE SOFTWARE, AND 
YOU MAY RETURN THE UNUSED SOFTWARE TO THE VENDOR FROM WHICH 
YOU ACQUIRED IT WITHIN THIRTY (30) DAYS AND REQUEST A REFUND 
OF THE LICENSE FEE, IF ANY, ALREADY PAID UPON SHOWING PROOF 
OF PAYMENT.  "YOU" MEANS THE NATURAL PERSON OR THE ENTITY 
THAT IS AGREEING TO BE BOUND BY THIS EULA, THEIR EMPLOYEES 
AND THIRD PARTY CONTRACTORS THAT PROVIDE SERVICES TO YOU.  
YOU SHALL BE LIABLE FOR ANY FAILURE BY SUCH EMPLOYEES AND 
THIRD PARTY CONTRACTORS TO COMPLY WITH THE TERMS OF THIS 
AGREEMENT.

1.0 GRANT AND USE RIGHTS FOR SOFTWARE.
1.1  License.  The Software is licensed, not sold.  
Subject to the terms of this EULA, Atomicorp hereby grants you 
a non-exclusive, non-transferable license, without rights to 
sublicense, to use the object code of the Software for the 
purpose as set forth in the applicable documentation for the 
Software and to the extent permitted by your payment of 
applicable license fees under an Atomicorp approved licensing 
model and/or your Software License Key subject to the 
software product specific terms specified in this EULA.  
Depending upon the model utilized to compute the applicable 
license fees paid by you to use the Software (whether per 
physical server, per Virtual server, per user, or any other 
Atomicorp approved licensing model), an applicable Software 
License subscription may limit your usage of the Software 
accordingly.  You may use the documentation accompanying the 
Software in connection with permitted uses of the Software.  

1.2  License Limitations.  You may not copy the Software 
except for a reasonable number of machine-readable copies of 
the Software for backup or archival purposes and except as 
expressly permitted in this EULA.  You may not remove any 
titles, trademarks or trade names, copyright notices, 
legends, or other proprietary markings on the Software.  You 
are not granted any rights to any trademarks or service 
marks of Atomicorp.  Atomicorp retains all rights not expressly 
granted to you.

1.3  Restrictions.  You may not (i) sell, lease, license, 
sublicense, distribute or otherwise transfer in whole or in 
part the Software or the Software License subscription to another 
party; (ii) provide, disclose, divulge or make available to, 
or permit use of the Software in whole or in part by, any 
third party (except Designated Administrative Access) 
without Atomicorp's prior written consent; or (iii) modify or 
create derivative works based upon the Software.  Except to 
the extent expressly permitted by applicable law, and to the 
extent that Atomicorp is not permitted by that applicable law 
to exclude or limit the following rights, you may not 
decompile, disassemble, reverse engineer, or otherwise 
attempt to derive source code from the Software, in whole or 
in part. You may not use Software to create products, 
technologies, software applications, web services in whole or 
in part, that directly compete with any Atomicorp product or 
technology. Competes is defined as creating or distributing 
software or services that provide similar or same functionality
as any Software or technology developed by Atomicorp. Atomicorp
reserves the right to revoke all rights and license privileges
of Licensee immediately upon any such infringement. Upon notice
of infringement, Licensee agrees to immediately destroy all
copies of Software and remove Software and references to
Software from all products, technologies and software applications.  
You may use the Software to conduct internal performance testing
and benchmarking studies, the results of which you (and not
unauthorized third parties) may publish or publicly disseminate;
provided that Atomicorp has reviewed and approved of the methodology,
assumptions and other parameters of the study in advance.  Please
contact Atomicorp at support@atomicorp.com to request such review.

1.4  GPL Software. You can redistribute and/or modify the GPL 
Software under the terms of the GPL.  You may obtain a copy 
of the source code corresponding to the binaries for the GPL 
Software (the "GPL Source Files") by downloading the GPL 
Source Files from Atomicorp's Web site at 
http://www.atomicorp.com/download/, or by 
sending a request, with your name and address, to Atomicorp at 
the address specified under the heading "Contact 
Information" below, in which case Atomicorp will mail a copy of 
the GPL Source Files to you on a CD or equivalent physical 
medium.  This offer to obtain a copy of the GPL Source Files 
is valid for one year from the date you acquired this 
Software product.

1.5  Audit Rights.  You will maintain accurate records as to 
your use of the Software as authorized by this Agreement, 
for at least two (2) years from the last day on which 
support and subscription services ("Services") expired for 
the applicable Software.  Atomicorp, or persons designated by 
Atomicorp, will, at any time during the period when you are 
obliged to maintain such records, be entitled to inspect 
such records and your computing devices, in order to verify 
that the Software is used by you in accordance with the 
terms of this Agreement and that you have paid the 
applicable license fees and Services fees for the Software; 
provided that Atomicorp may conduct no more than one (1) audit 
in any twelve (12) month period.  You shall promptly pay to 
Atomicorp any underpayments revealed by any such audit.  Any 
such audit will be performed at Atomicorp's expense during 
normal business hours, provided that you shall promptly 
reimburse Atomicorp for the cost of such audit and any 
applicable fees if such audit reveals an underpayment by you 
of more than five percent (5%) of the amounts payable by you 
to Atomicorp for the period audited.

2.0 TITLE

Atomicorp retains all right, title, and interest in and to the 
Software and the Software License Key and in all related 
copyrights, trade secrets, patents, trademarks, and any 
other intellectual and industrial property and proprietary 
rights, including registrations, applications, renewals, and 
extensions of such rights.

3.0  SUPPORT AND SUBSCRIPTION SERVICES
Atomicorp will provide email support services under this 
EULA.  Extended support services may be negotiated with 
Atomicorp directly. Email support is available between
the hours of 9am and 5pm EST. 

If you use spam filtering, please ensure that you allow support@atomicorp.com
to enable us to respond to your support requests. It is your responsibility to
ensure that this is allowed. By agreeing to this EULA you are accepting full 
risk and responsibility for communication from our support organization, and 
lose any any all rights of rebuke therein.

This EULA does not give you any rights to any updates 
or upgrades to the Software or to any extensions or 
enhancements to the Software developed by Atomicorp outside of
the Atomic Secured Linux subscription period.  
in the future.  

If you have purchased Atomicorp support 
and subscription services with the Software, these services 
are provided to you under the Support Contract Terms and 
Conditions posted on Atomicorp's Web site at   
http://www.atomicorp.com/support/  and by accepting the terms 
of this EULA you are accepting these Support Contract Terms 
and Conditions.  Any supplemental software code or related 
materials that Atomicorp provides to you as part of any support 
and subscription services are to be considered part of the 
Software and are subject to the terms and conditions of this 
EULA.  Atomicorp may use any technical information you provide 
to Atomicorp for any Atomicorp business purposes without 
restriction, including for product support and development. 

Atomicorp will not use information in a form that personally 
identifies you.



4.0  TERMINATION

4.1  Termination.  Atomicorp may terminate this EULA immediately 
and without notice if you fail to comply with any term of 
this EULA.

4.2  Effect of Termination.  In the event of termination, you 
must destroy all copies of the Software.  In addition you must
remove all copies of the Software, including all backup copies, 
from all computers and terminals on which it is installed.  From 
time to time, Atomicorp may change the terms of this EULA.  
Atomicorp will notify you of such change.  Your continued use 
of the Software will indicate your agreement to the change.

5.  LIMITED WARRANTY AND LIMITATION OF LIABILITY

5.1  Limited Warranty. Atomicorp warrants that the media, if 
any, on which the Software is delivered will be free of 
defects and that the Software will substantially conform to 
the description contained in the applicable end user 
documentation in each case for a period of 90 days after the 
date of activation of the Software subscription.  EXCEPT FOR 
THE PRECEDING EXPRESS LIMITED WARRANTY, TO THE MAXIMUM 
EXTENT PERMITTED BY APPLICABLE LAW, ATOMICORP AND ITS LICENSORS 
PROVIDE THE SOFTWARE WITHOUT ANY WARRANTIES OF ANY KIND, 
EXPRESS, IMPLIED, STATUTORY, OR IN ANY OTHER PROVISION OF 
THIS EULA OR COMMUNICATION WITH YOU, AND ATOMICORP AND ITS 
LICENSORS SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-
INFRINGEMENT.

5.2  TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO 
EVENT WILL ATOMICORP AND ITS LICENSORS BE LIABLE FOR ANY LOST 
PROFITS OR BUSINESS OPPORTUNITIES, LOSS OF USE, BUSINESS 
INTERRUPTION, LOSS OF DATA, OR ANY OTHER INDIRECT, SPECIAL, 
INCIDENTAL, OR CONSEQUENTIAL DAMAGES UNDER ANY THEORY OF 
LIABILITY, WHETHER BASED IN CONTRACT, TORT, NEGLIGENCE, 
PRODUCT LIABILITY, OR OTHERWISE.  BECAUSE SOME JURISDICTIONS 
DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR 
CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE PRECEDING 
LIMITATION MAY NOT APPLY TO YOU.  ATOMICORP AND ITS LICENSORS' 
LIABILITY UNDER THIS EULA WILL NOT, IN ANY EVENT, EXCEED THE 
LICENSE FEES, IF ANY, PAID BY YOU FOR THE SOFTWARE LICENSED 
TO YOU UNDER THIS EULA. THE FOREGOING LIMITATIONS SHALL 
APPLY TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, 
REGARDLESS OF WHETHER ATOMICORP OR ITS LICENSORS HAVE BEEN 
ADVISED OF THE POSSIBILITY OF SUCH DAMAGES AND REGARDLESS OF 
WHETHER ANY REMEDY FAILS OF ITS ESSENTIAL PURPOSE. 

6.0 GENERAL

6.1  Entire Agreement. This Agreement sets forth Atomicorp's 
entire liability and your exclusive remedy with respect to 
the Software and supersedes the terms of any purchase orders 
and any other communications or advertising with respect to 
the Software. You acknowledge that this Agreement is a 
complete statement of the agreement between you and Atomicorp 
with respect to the Software, and that there are no other 
prior or contemporaneous understandings, promises, 
representations, or descriptions with respect to the 
Software.  

6.2  Headings. Headings under this EULA are intended only 
for convenience and shall not affect the interpretation of 
this EULA.

6.3  Waiver and Modification.  No failure of either party to 
exercise or enforce any of its rights under this EULA will 
act as a waiver of those rights.  This EULA may only be 
modified, or any rights under it waived, by a written 
document executed by the party against which it is asserted.

6.4  Severability.  If any provision of this EULA is found 
illegal or unenforceable, it will be enforced to the maximum 
extent permissible, and the legality and enforceability of 
the other provisions of this EULA will not be affected.

6.5  Governing Law.  This EULA will be governed by 
Virginia law and the United States of America, without 
regard to its choice of law principles. The United Nations 
Convention for the International Sale of Goods shall not 
apply.  Jurisdiction shall exclusively reside in the courts
within Fairfax County, Virginia.

6.6  Government Restrictions.  You may not export or re-
export the Software except in compliance with the United 
States Export Administration Act and the related rules and 
regulations and similar non-U.S. government restrictions, if 
applicable.  The Software and accompanying documentation are 
deemed to be "commercial computer software" and "commercial 
computer software documentation," respectively, pursuant to 
DFAR Section 227.7202 and FAR Section 12.212(b), as 
applicable.  Any use, modification, reproduction, release, 
performing, displaying, or disclosing of the Software by the 
U.S. Government shall be governed solely by the terms of 
this EULA.

6.7  Contact Information.  If you have any questions about 
this EULA, or if you want to contact Atomicorp for any reason, 
please direct all correspondence to: 
Atomicorp, Inc., 
14121 Parke-long Court, Suite 220 
Chantilly, Virginia 20151

or email support@atomicorp.com.

6.8  Other. Atomicorp and Atomic Secured Linux are trademarks and/or
registered trademarks of Atomicorp, Inc. in the United States and/or 
various jurisdictions.  

EOF

check_input  "Do you agree to these terms (yes/no) [Default: yes]" "yes|no"  "yes"

if [ $INPUTTEXT != "yes" ]; then
	echo "
	Exiting install, License was not accepted
	"  | tee -a $LOG
	exit 1
fi
echo "NOTICE: User accepted License" >> $LOG

fi

#echo
#posix_acl_check

echo



echo -n "Checking for free space:"
freespace_check "/var" "4000"
freespace_check "/usr" "500"
freespace_check "/tmp" "10"
freespace_check "/etc" "100"
echo " Done"

echo -n "Checking for memory requirements: "
memory=$(free |awk '/Mem:/ {print $2}')
if [ $memory -lt 900000 ]; then
	echo "Failed" | tee -a $LOG
	echo "	a minimuim of 1G of memory is required for ASL." | tee -a $LOG

	exit 1
else
	echo "PASS"
fi

echo -n "Checking sudo: "
/usr/bin/sudo true >/dev/null 2>&1
if [ $? -eq 0 ]; then
        echo PASS
else
        echo FAIL
        echo
        echo "Error: Sudo execution failed. " | tee -a $LOG
        echo
        /usr/bin/sudo true
        echo
        echo "Contact your Operating System provider for support."
        echo
        exit 1
fi

# checking for mysql old_passwords
echo -n "Checking database: "
if grep -q ^old_password /etc/my.cnf ; then
	echo FAIL
	echo "  Error: This setting is not supported for server installations."
	echo "  and must be disabled in order to complete".
	echo "  Exiting installer."
	exit 1
	
else
	echo PASS
	
fi




if [ -f /etc/yum.repos.d/asl.repo ]; then
	rm -f /etc/yum.repos.d/asl.repo
fi

if [ -f /etc/yum.repos.d/tortix-kernel.repo ]; then
	rm -f /etc/yum.repos.d/tortix-kernel.repo
fi

if [ -f /etc/yum.repos.d/tortix-kernel-xen.repo ]; then
	rm -f /etc/yum.repos.d/tortix-kernel-xen.repo
fi


# Check for 3rd party repos
ALT_REPO=$(yum -v -C repolist |awk -F: '/Repo-id/  {print $2}' |egrep -v "^ (asl-|atomic|base|extras|updates|tortix|cloudlinux|epel|MariaDB10)")
RETVAL=$?
if [ $RETVAL -lt 1 ]; then
	echo
	echo
	echo "WARNING: 3rd party yum repositories could conflict during ASL configuration." | tee -a $LOG
	echo "The following repositories were detected:" | tee -a $LOG
	echo $ALT_REPO | tee -a $LOG
	echo
	echo "Recommendation: Temporarily disable these repositories before continuing the installation."
	echo

	if [ ! $AUTO ]; then
		check_input "  Do you wish to continue? (yes/no) [Default: no]" "yes|no" "no"
		
		if [ "$INPUTTEXT" == "no" ]; then
			echo
			echo "Exiting..."
			echo
			exit 1
		fi

		check_input "  Are you sure you wish to continue? (yes/no) [Default: no]" "yes|no" "no"

		if [ "$INPUTTEXT" == "no" ]; then
			echo
			echo "Exiting..."
			echo
			exit 1
		fi
	fi

fi

# Check for non-standard mysql
#M_LIST=$(rpm -qa |grep -i ^mysql |egrep -v "mysql-|^mysqltuner|^mysqlclient|^MySQL-")
#RETVAL=$?
#if [ $RETVAL -lt 1 ]; then
#	echo
#	echo
#	echo "WARNING: 3rd party mysql packages detected. ASL is supported with the" | tee -a $LOG
#	echo "official version of MySQL provided by Redhat, Centos and Atomicorp for"| tee -a $LOG
#	echo "that platform and distribution. Installation may not be possible on "| tee -a $LOG
#	echo "this system."| tee -a $LOG
#	echo
#        echo "The following packages were detected:"| tee -a $LOG
#        echo $M_LIST| tee -a $LOG
#        echo
#        echo
#
#	if [ ! $AUTO ]; then
#		check_input "  Do you wish to continue? (yes/no) [Default: no]" "yes|no" "no"
#		if [ "$INPUTTEXT" == "no" ]; then
#			echo
#			echo "Exiting..."
#			echo
#			exit 1
#		fi
#
#		check_input "  Are you sure you wish to continue? (yes/no) [Default: no]" "yes|no" "no"
#
##		if [ "$INPUTTEXT" == "no" ]; then
#			echo
#			echo "Exiting..."
##			echo
#			exit 1
#		fi
#	fi
#
#	echo "WARNING: 3rd party Mysql detected, user accepted risk." >> $LOG
#
#
#fi

if [ -d /etc/csf ]; then
	echo
	echo
	echo "WARNING: Configserver (CSF) detected. ASL does not support CSF."
	echo "CSF or other 3rd party WAF / Firewall management tools should be removed"
	echo "before installing ASL."
	echo
	echo


	if [ ! $AUTO ]; then
		check_input "  Would you like to remove csf? (yes/no) [Default: yes]" "yes|no" "yes"
		if [ "$INPUTTEXT" == "yes" ]; then
			if [ -f /etc/csf/uninstall.sh ]; then
				/etc/csf/uninstall.sh
			fi 
		else
			check_input "  Do you wish to continue? (yes/no) [Default: no]" "yes|no" "no"
			if [ "$INPUTTEXT" == "no" ]; then
				echo
				echo "Exiting..."
				echo
				exit 1
			fi

			check_input "  Are you sure you wish to continue? (yes/no) [Default: no]" "yes|no" "no"

			if [ "$INPUTTEXT" == "no" ]; then
				echo
				echo "Exiting..."
				echo
				exit 1
			fi

			
		fi
	fi

	echo
	echo "WARNING: CSF detected, user accepted risk " >> $LOG
	echo

fi

echo
echo -n "Checking for core updates: "
Y_LIST=$(yum list updates |wc -l)
if [ $Y_LIST -gt 50 ]; then
	echo "Pending updates FAIL (count: $Y_LIST)" >> $LOG

	echo FAIL | tee -a $LOG
	echo  | tee -a $LOG
	echo "The system appears to be missing Operating System patches and is significantly out of date. ($Y_LIST updates pending)" | tee -a $LOG
	echo "This environment may be so out of date that it will not be supportable." | tee -a $LOG
	echo | tee -a $LOG
	echo "Recommendation: Halt the installation, and investigate the unapplied Operating System patches to the system" | tee -a $LOG
	echo | tee -a $LOG

	if [ ! $AUTO ]; then
		check_input "  This environment is UNSUPPORTED. Do you wish to continue? (yes/no) [Default: no]" "yes|no" "no"
		if [ "$INPUTTEXT" == "no" ]; then
			echo
			echo "Exiting..."
			echo
			exit 1
		fi
	fi

	echo
	echo
	echo
	echo "WARNING: Pending updates, user accepted risk " >> $LOG

else
	echo "OK"
	echo "Pending updates OK (count: $Y_LIST)" >> $LOG
fi

echo -n "Performing Basic environment checks: " | tee -a $LOG

# apache version test
#if [ -f /usr/sbin/httpd ]; then
#	/usr/sbin/httpd -v |grep Apache/2.4
#	if [ $? -eq 0 ]; then
#		echo
#		echo "ERROR: Apache 2.4 environment detected."
#		echo "This version of apache is not supported at this time."
##		echo "Exiting..."
#		echo
#		exit 1
#		
#	fi
#fi

if [ -d /usr/local/directadmin ] ; then
   echo "  DirectAdmin detected..." | tee -a $LOG
   DIRECTADMIN=1
   SOURCEINSTALL=1
   if [ -f /usr/sbin/httpd ] ; then
     HTTPD=/usr/sbin/httpd
   else

     echo "  Path to apache could not be determined. This is a custom environment" | tee -a $LOG
     echo "  Please contact the services group at support@atomicorp.com for a custom" | tee -a $LOG
     echo "  installation quote." | tee -a $LOG
     echo
     exit 1
   fi

  # Test X: determine httpd config file location
  if [ -f /etc/httpd/conf/httpd.conf ]; then
   HTTP_CONF="/etc/httpd/conf/httpd.conf"
  fi

elif [ -d /usr/local/cpanel ]; then
  echo "  cpanel Detected..." | tee -a $LOG
  CPANEL=1
  SOURCEINSTALL=1
   if [ -f /usr/local/apache/bin/httpd ] ; then
     HTTPD=/usr/local/apache/bin/httpd
   else

     echo "  Path to apache could not be determined. This is a custom environment" | tee -a $LOG
     echo "  Please contact the services group at support@atomicorp.com for a custom" | tee -a $LOG
     echo "  installation quote." | tee -a $LOG
     echo
     exit 1
   fi

  # Test X: determine httpd config file location
  HTTP_CONF="/usr/local/apache/conf/httpd.conf"

else
  echo "Standard" | tee -a $LOG

fi
echo | tee -a $LOG



# Main
if [ ! $AUTO ]; then
	CONFIGURED=no
fi

if [ ! -f /var/asl/bin/asl ]; then
        if [ -f /etc/asl/config ]; then

		mv /etc/asl/config /etc/asl/config.preupgrade
        fi 

fi

if [ -f /etc/asl/config ] ; then
  	source /etc/asl/config
fi


if [ "$CONFIGURED" != "yes" ]; then
  # ---------  from tortix.key
  if [ -f /etc/asl/tortix.key ]; then
  	TC_TARGET="www.atomicorp.com/channels/rules/plesk/README"
	STEXT=`base64 -d /etc/asl/tortix.key`
	USERNAME=$(php -r "\$z = unserialize('"$STEXT"'); echo \$z[\"login\"] ; ")
	PASSWORD=$(php -r "\$z = unserialize('"$STEXT"'); echo \$z[\"pass\"] ; ")
	export USERNAME
	echo "Username: $USERNAME" >> $LOG
  # ---------  from stdin
  else
    	TC_TARGET="www.atomicorp.com/channels/asl-3.0/README"
	echo -n "Enter subscription Username: " | tee -a $LOG
	read USERNAME < $INSTALL_TTY
	export USERNAME
	echo "Username: $USERNAME" >> $LOG
	
	if [ "$USERNAME" == "" ]; then
	  echo "Exiting: Username is blank. " | tee -a $LOG
	  echo
	  exit 1
	fi
	
	PASSCONFIRMED=0
	failed=0
	
	while [ $PASSCONFIRMED -lt 1 ]; do
	  if [ $failed -gt 2 ]; then
	    echo "Exiting: too many failed attempts." |tee -a $LOG
	    echo
	    exit 1
	  fi
	
	  echo -n "Enter Subscription Password: "
	  unset PASSWORD
	  read -s PASSWORD < $INSTALL_TTY
	  #      while IFS= read -r -s -n1 pass <$INSTALL_TTY ; do
	  #              if [[ -z $pass ]]; then
	  #                      echo
	  #                      break
	  #              else
	  #                      echo -n '*'
	  #                      PASSWORD+=$pass
	  #              fi
	  #      done
	
	  echo


      if [ "$PASSWORD" == "" ]; then
        echo "Exiting: Password is blank..." | tee -a $LOG
        echo 
        exit 1
      fi

      #if ! isValid "$PASSWORD"; then
      #	echo "Exiting: Only Alpha-Numeric passwords are supported..." | tee -a $LOG
      #	echo
      #	exit 1
      #    fi

      unset PASSWORD2
      echo -n "Re-Enter Subscription Password: "
	  read -s PASSWORD2 < $INSTALL_TTY
        #while IFS= read -r -s -n1 pass <$INSTALL_TTY; do
        #        if [[ -z $pass ]]; then
        #                echo
        #                break
        #        else
        #                echo -n '*'
        #                PASSWORD2+=$pass
        #        fi
        #done
	  echo

      if [ "$PASSWORD" == "$PASSWORD2" ]; then
        PASSCONFIRMED=1
      else
        failed=$(( $failed + 1 ))
        echo "Sorry, passwords do not match." | tee -a $LOG
        echo
      fi
    done
  fi
fi

# Placeholder
if [ -d /etc/asl ]; then
	touch /etc/asl/tortix.key
fi

ENCPASSWORD=$(rawurlencode $PASSWORD)


#TEST_CREDENTIALS=$($GET -nv https://$USERNAME:$ENCPASSWORD@www.atomicorp.com/channels/asl-3.0/README -O -  2>&1)
TEST_CREDENTIALS=$($GET -nv https://$USERNAME:$ENCPASSWORD@$TC_TARGET -O - 2>&1)

echo -n "Verifying account: " | tee -a $LOG
if [ "$TEST_CREDENTIALS" == "Authorization failed." ]; then
  echo " Failed" | tee -a $LOG
  echo
  echo "   ERROR: ASL Username/Password credentials are incorrect or this license has expired." | tee -a $LOG
  echo "   For more information, please see this FAQ:" | tee -a $LOG
  echo "   https://www.atomicorp.com/wiki/index.php/ASL_FAQ#HTTP_Error_401:_Authorization_Required_Trying_other_mirror.
" | tee -a $LOG
  echo 
  exit 1
else
  echo "  Passed" | tee -a $LOG
fi


# Amazon EL clone. Fix missing redhat-release
if [ -f /etc/system-release ]; then
	if [ ! -f /etc/redhat-release ]; then
		echo "Fix for missing redhat-release" >> $LOG
  		ln -sf /etc/system-release /etc/redhat-release
	fi
fi

if [ ! -f /etc/redhat-release ]; then
	echo
  	echo "Error: /etc/redhat-release was not detected" | tee -a $LOG
	echo
	exit 1
fi

RELEASE=`cat /etc/redhat-release | awk -F\( '{print $1}'`
echo "Release is: $RELEASE" >> $LOG


# EL3, EL4, and Fedora
if egrep -q "^Fedora|release 3|release 4" /etc/redhat-release ; then
	cat /etc/redhat-release
	echo "This platform is no longer supported..." | tee -a $LOG
	echo "Exiting..."
	exit 1
# EL5
elif egrep -q "release 5|release 2011" /etc/redhat-release ; then
  DIST="el5"
  DIR=centos/5
# EL6
elif egrep -q "release 6|release 2012" /etc/redhat-release ; then
  DIST="el6"
  DIR=centos/6
# EL7
elif egrep -q "release 7" /etc/redhat-release ; then
  	DIST="el7"
  	DIR=centos/7

else 
  echo "Error: Unable to determine distribution type. Please send the contents of /etc/redhat-release to support@atomicorp.com" | tee -a $LOG
  exit 1
fi

if [ ! -f /usr/bin/yum ]; then
	echo
  	echo "Error: Yum was not detected. Contact your provider for support." | tee -a $LOG
  	echo
	exit 1
else
  YUM=1
fi


## yum, make sure yum is up to date
echo -n "Ensuring yum is up to date: " | tee -a $LOG
/usr/bin/yum -y upgrade yum >> $LOG 2>&1
echo "Done" | tee -a $LOG

## check for perl (minimal installs)
echo -n "Checking for perl: " | tee -a $LOG
if  [ ! -f /usr/bin/perl ]; then
  /usr/bin/yum -y install perl >> $LOG 2>&1|| exit 1
fi
echo "Done" | tee -a $LOG

# Make sure selinux is as off as we can make it
if [ -x /usr/sbin/setenforce ]; then
  /usr/sbin/setenforce 0 >/dev/null 2>&1
  if [ -f /etc/sysconfig/selinux ]; then
    /usr/bin/perl -p -i -e "s/SELINUX=.*/SELINUX=disabled/g" /etc/sysconfig/selinux
  fi
  if [  -f /etc/selinux/config ]; then
    /usr/bin/perl -p -i -e "s/SELINUX=.*/SELINUX=disabled/g" /etc/selinux/config
  fi
fi

echo -n "Installing the Atomic GPG key: " |tee -a $LOG
if [ !  -f /etc/pki/rpm-gpg/RPM-GPG-KEY.art.txt ]; then
  	if [ ! -d /etc/pki/rpm-gpg ]; then
    	mkdir -p /etc/pki/rpm-gpg/
  	fi
  	wget -q http://www.atomicorp.com/RPM-GPG-KEY.art.txt -O /etc/pki/rpm-gpg/RPM-GPG-KEY.art.txt   >> $LOG 2>&1
	rm -f RPM-GPG-KEY.art.txt
fi
echo "OK" | tee -a $LOG
/bin/rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY.art.txt

if [ !  -f /etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt ]; then
        if [ ! -d /etc/pki/rpm-gpg ]; then
        mkdir -p /etc/pki/rpm-gpg/
        fi
        wget -q http://www.atomicorp.com/RPM-GPG-KEY.atomicorp.txt -O /etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt   >> $LOG 2>&1
fi
/bin/rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt


if [ ! -d /etc/asl ]; then
	mkdir /etc/asl
fi


cat  << EOF > /etc/yum.repos.d/asl.repo
[asl-4.0]
name=Atomicorp - $releasever - Atomic Secured Linux 4.0
mirrorlist=file:///etc/asl/asl-4.0-mirrorlist
priority=1
enabled=1
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
	file:///etc/pki/rpm-gpg/RPM-GPG-KEY.art.txt

gpgcheck=1
$KERNEL

[asl-4.0-testing]
name=Atomicorp - $releasever - Atomic Secured Linux 4.0 (Testing)
mirrorlist=file:///etc/asl/asl-4.0-testing-mirrorlist
priority=1
enabled=0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
	file:///etc/pki/rpm-gpg/RPM-GPG-KEY.art.txt
gpgcheck=1
$KERNEL
EOF

#cat  << EOF > /etc/yum.repos.d/tortix.repo
#[tortix]
#name=Atomicorp - $releasever - Atomic Secured Linux 4.0
#mirrorlist=file:///etc/asl/tortix-mirrorlist
#priority=1
#enabled=1
#gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY.atomicorp.txt
#gpgcheck=1
#EOF



cat << EOF > /etc/asl/asl-4.0-mirrorlist
https://$USERNAME:$ENCPASSWORD@www2.atomicorp.com/channels/asl-4.0/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www3.atomicorp.com/channels/asl-4.0/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www5.atomicorp.com/channels/asl-4.0/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www6.atomicorp.com/channels/asl-4.0/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www8.atomicorp.com/channels/asl-4.0/$DIR/$ARCH
EOF

cat << EOF > /etc/asl/asl-4.0-testing-mirrorlist
https://$USERNAME:$ENCPASSWORD@www2.atomicorp.com/channels/asl-4.0-testing/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www3.atomicorp.com/channels/asl-4.0-testing/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www5.atomicorp.com/channels/asl-4.0-testing/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www6.atomicorp.com/channels/asl-4.0-testing/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www8.atomicorp.com/channels/asl-4.0-testing/$DIR/$ARCH
EOF

cat << EOF > /etc/asl/tortix-mirrorlist
https://$USERNAME:$ENCPASSWORD@www2.atomicorp.com/channels/tortix/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www3.atomicorp.com/channels/tortix/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www5.atomicorp.com/channels/tortix/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www6.atomicorp.com/channels/tortix/$DIR/$ARCH
https://$USERNAME:$ENCPASSWORD@www8.atomicorp.com/channels/tortix/$DIR/$ARCH
EOF



# Source install
if [ $SOURCEINSTALL -ge 1 ]; then

	# Litespeed check
	if [ -f /usr/local/cpanel/whostmgr/docroot/cgi/lsws/chkLSRunning.sh ]; then

		LITESPEED=1
		echo
		echo "Litespeed installation detected." | tee -a $LOG
		echo "  UNSUPPORTED: Litespeed is not supported." | tee -a $LOG
		echo

		check_input "  This environment is UNSUPPORTED. Do you wish to continue? (yes/no) [Default: no]" "yes|no" "no"

		if [ "$INPUTTEXT" == "no" ]; then
			echo "  Exiting...." | tee -a $LOG
			echo
			exit
		fi
		echo "WARNING: User accepted unsupported litespeed risk." >> $LOG

	else

		# Module check
		echo -n "Verifying mod_unique_id: " |tee -a $LOG
		$HTTPD -l |grep -q unique >> $LOG
		RETVAL=$?
		if [ ! "$RETVAL" = 0 ]; then
	  		echo "Not found."
	  		if [ $CPANEL ]; then
				echo
				echo "  ASL will attempt to rebuild apache with uniqueid support later " |tee -a $LOG
				echo "  in the installation" |tee -a $LOG
				echo
				BUILD_UNIQUEID=1
			else
	  			echo "  mod_unique_id support in apache is required. You will need to" |tee -a $LOG
	  			echo "  rebuild apache with support to continue installing ASL." |tee -a $LOG
				echo
				exit 1
	  		fi
	  		echo
	  		echo
		else
	  		echo "passed." |tee -a $LOG
	  		echo
		fi

	fi

	# Clear work directory
	if [ -d /root/atomic ]; then
	  rm -rf /root/atomic
	fi

	mkdir /root/atomic

	cd /root/atomic/

	# Prep yum
	yum clean all >> $LOG

	# Prep dev tools
	# cpanel has added git-cpanel which conflicts with Development Tools now
#	yum -y --disableexcludes=all --skip-broken groupinstall "Development Tools" |tee -a $LOG 
#	if [ ${PIPESTATUS[0]} -ge 1 ]; then
#		echo "Yum Development Tools installation failed." |tee -a $LOG
#		exit 1
#	fi

	# secondary error checking
	if [ ! -f /usr/bin/rpmbuild ]; then
		yum -y --disableexcludes=all --skip-broken install rpm-build  |tee -a $LOG 
		if [ ${PIPESTATUS[0]} -ge 1 ]; then

			echo "	ERROR: rpmbuild could not be installed. Contact your OS vendor for further assistance." | tee -a $LOG
			exit 1
		fi
	fi



	# Fix 1: Correct bash profile, move cpanel functions to a separate file
	if [ $CPANEL ]; then
		if [ "$DIST" == "el6" ]; then
			yum -y --disableexcludes=all --skip-broken  install libcurl-devel  | tee -a $LOG
			if [ ${PIPESTATUS[0]} -ge 1 ]; then
				echo "Yum libcurl-devel install failed." | tee -a $LOG
				exit 1
			fi
		fi
    		# copy over mangled bashrc
    		$GET -q http://www.atomicorp.com/installers/cpanel/bashrc | tee -a $LOG
		if [ ${PIPESTATUS[0]} -ge 1 ]; then
			exit 1
		fi
    		$GET -q http://www.atomicorp.com/installers/cpanel/profile-cpanel.sh | tee -a $LOG
		if [ ${PIPESTATUS[0]} -ge 1 ]; then
			exit 1
		fi

    		# import cpanel functions to /etc/profile.d/cpanel.sh
    		chattr -i /etc/bashrc
    		install -m 0755 bashrc /etc/bashrc
    		install -m 0755 profile-cpanel.sh /etc/profile.d/cpanel.sh

    		source /etc/profile
    		source /etc/bashrc >/dev/null 2>&1

    		# Fix 2: Correct /etc/init.d/mysqld script
    		ln -sf /etc/init.d/mysql /etc/init.d/mysqld
  	fi


	# mysqlclient?
        if rpm -q MySQL-server; then
                # ver check
                mysqlver=$(rpm -q MySQL-server |awk -F. '{print $1 "." $2}')
		# Probably not needed for anything (el5 is linked against client16)
                if [ "$mysqlver" == "MySQL-server-5.1" ]; then
                       # yum --disableexcludes=all -y install mysqlclient18 | tee -a $LOG
		#	if [ ${PIPESTATUS[0]} -ge 1 ]; then
		#		echo
		#		echo "Error: Could not install mysqlclient18" |tee -a $LOG
		#		exit 1
#
#			fi
			echo
                elif [ "$mysqlver" == "MySQL-server-5.5" ]; then
                        yum --disableexcludes=all -y install mysqlclient16  | tee -a $LOG #for el6
			if [ ${PIPESTATUS[0]} -ge 1 ]; then
				echo
				echo "Error: Could not install mysqlclient16" |tee -a $LOG
				exit 1
			fi

                fi
        fi

        #if rpm -q MySQL50-server; then
        #        yum --disableexcludes=all -y install mysqlclient18 | tee -a $LOG 
	#	if [ ${PIPESTATUS[0]} -ge 1 ]; then
	#		echo
	#		echo "Error: Could not install mysqlclient18" |tee -a $LOG
	#		exit 1
	#	fi
        #fi

        if rpm -q MySQL51-server; then
                #yum --disableexcludes=all -y install mysqlclient18 | tee -a $LOG 
		#if [ ${PIPESTATUS[0]} -ge 1 ]; then
		#	echo
		#	echo "Error: Could not install mysqlclient18" |tee -a $LOG
		#	exit 1
		#fi

                if [ "$DIST" == "el5" ]; then
                        yum --disableexcludes=all -y install mysqlclient15  | tee -a $LOG #for el6
			if [ ${PIPESTATUS[0]} -ge 1 ]; then
				echo
				echo "Error: Could not install mysqlclient15" |tee -a $LOG
				exit 1
			fi
                fi

        fi

        if rpm -q MySQL55-server; then
                if [ "$DIST" != "el7" ]; then
			yum --disableexcludes=all -y install mysqlclient16  | tee -a $LOG #for el6
			#yum --disableexcludes=all -y install mysqlclient18  | tee -a $LOG #for el6
			if [ ${PIPESTATUS[0]} -ge 1 ]; then
				echo
				echo "Error: Could not install mysqlclient16 or mysqlclient18" |tee -a $LOG
				exit 1
			fi
			if [ "$DIST" == "el5" ]; then
				yum --disableexcludes=all -y install mysqlclient15  | tee -a $LOG #for el6
				if [ ${PIPESTATUS[0]} -ge 1 ]; then
					echo
					echo "Error: Could not install mysqlclient15" |tee -a $LOG
					exit 1
				fi
			fi
		fi
        fi

        if rpm -q MySQL56-server; then
                yum --disableexcludes=all -y install mysqlclient16  | tee -a $LOG #for el6
                #yum --disableexcludes=all -y install mysqlclient18  | tee -a $LOG #for el6
		if [ ${PIPESTATUS[0]} -ge 1 ]; then
			echo
			echo "Error: Could not install mysqlclient16 or mysqlclient18" |tee -a $LOG
			exit 1
		fi
                if [ "$DIST" == "el5" ]; then
                        yum --disableexcludes=all -y install mysqlclient15  | tee -a $LOG #for el6
			if [ ${PIPESTATUS[0]} -ge 1 ]; then
				echo
				echo "Error: Could not install mysqlclient15" |tee -a $LOG
				exit 1
			fi
		fi
        fi







# Handled by asl -c now
	# Test X: install tortix web daemon
#	if [ -f /etc/yum.repos.d/atomic.repo ]; then
#		rpm --quiet -q tortixd || yum --disableexcludes=all --disablerepo=atomic -y install tortixd tortixd-mod_ssl asl-php asl-php-mysql asl-php-gd | tee -a $LOG
#		
#	else
#		rpm --quiet -q tortixd || yum --disableexcludes=all -y install tortixd tortixd-mod_ssl asl-php asl-php-mysql asl-php-gd | tee -a $LOG
#	fi

        # WAF build Start
	# Test X: install pcre & pcre-devel
	rpm --quiet -q pcre || yum --disableexcludes=all -y install pcre | tee -a $LOG
	rpm --quiet -q pcre-devel || yum --disableexcludes=all -y install pcre-devel | tee -a $LOG


	# Fix X: Reduce spurious header files that cause conflicts
	if [ -f /usr/local/apache/include/pcre.h ]; then
		echo "/usr/local/apache/include/pcre.h detected.... removing deprecated file" | tee -a $LOG
		rm -f /usr/local/apache/include/pcre.h
	fi


  # TODO: Test X: Configure rule storage directory location & default config
  if [ ! -d /etc/httpd/modsecurity.d ]; then
    mkdir -p /etc/httpd/modsecurity.d
  fi

  if [ ! -d /etc/httpd/conf.d ]; then
    mkdir -p  /etc/httpd/conf.d
  fi


# Test X: Support packages
  if ! rpm --quiet -q asl-stream-client; then
	yum --disableexcludes=all -y install asl-stream-client clamd rkhunter chkrootkit paxtest| tee -a $LOG
        if [ ${PIPESTATUS[0]} -ge 1 ]; then
		echo
		echo "Error: Could not install  asl-stream-client clamd rkhunter chkrootkit paxtest" |tee -a $LOG
		exit 1
        fi

  fi

  if ! rpm --quiet -q psmon; then

    if [ -h /usr/bin/perl ]; then
	echo "ERROR: damaged /usr/bin/perl detected. " | tee -a $LOG
	echo "  Cpanel has broken perl on your system, contact cpanel for support.  " | tee -a $LOG
	echo "  PSMON cannot be installed... " | tee -a $LOG
	echo "  logging data, please stand by" | tee -a $LOG
        sleep 10
    else
	yum --disableexcludes=all -y install psmon | tee -a $LOG
        if [ ${PIPESTATUS[0]} -ge 1 ]; then
		echo
		echo "Error: Could not install psmon" |tee -a $LOG
		exit 1
        fi
    fi

  fi

# Test X:  OSSEC
  DISABLEREPO=""
  if [ -f /etc/yum.repos.d/atomic.repo ]; then
    DISABLEREPO="--disablerepo=atomic"
  fi
	# Handled by asl -c now

#  rpm --quiet -q ossec-hids-server || yum $DISABLEREPO -y  --disableexcludes=all install ossec-hids-server | tee -a $LOG
#  rpm --quiet -q ossec-hids-server && yum $DISABLEREPO -y  --disableexcludes=all upgrade ossec-hids-server | tee -a $LOG

  # Test X: download & install asl 
  if ! rpm --quiet -q asl; then
	 yum -y --disableexcludes=all install asl | tee -a $LOG
         if [ ${PIPESTATUS[0]} -ge 1 ]; then
                        echo
                        echo "Error: Could not install ASL" |tee -a $LOG
                        exit 1
         fi
  else 
	 yum -y --disableexcludes=all upgrade asl | tee -a $LOG
         if [ ${PIPESTATUS[0]} -ge 1 ]; then
                        echo
                        echo "Error: Could not upgrade ASL" |tee -a $LOG
                        exit 1
         fi

  fi

  # Permissions check
  if [ $CPANEL ]; then
    	chown nobody.nobody /var/asl/data/msa
    	chown nobody.nobody /var/asl/data/audit
    	chown nobody.nobody /var/asl/data/suspicious
    	#chmod o-rx -R /var/asl/data/*
    	#chmod ug+rwx -R /var/asl/data/*


	if [ ! $LITESPEED ]; then
		if [ -f /scripts/preeasyapache ]; then
			if ! egrep "template-cpanel-preeasyapache-hook.*ASL_HOOK" /scripts/preeasyapache ; then
				echo "/var/asl/data/templates/template-cpanel-preeasyapache-hook #ASL_HOOK" >> /scripts/preeasyapache
		
			fi
		else
			install -m0755 /var/asl/data/templates/template-cpanel-preeasyapache /scripts/preeasyapache
		fi

		if [ -f /scripts/posteasyapache ]; then
			if ! egrep "template-cpanel-apache-hook.*ASL_HOOK" /scripts/posteasyapache ; then
				echo "/var/asl/data/templates/template-cpanel-apache-hook #ASL_HOOK" >> /scripts/posteasyapache
			fi
		else
			install -m0755 /var/asl/data/templates/template-cpanel-posteasyapache /scripts/posteasyapache
		fi

		# Install modules 
		/scripts/easyapache --build | tee -a $LOG
	fi
  elif [ $DIRECTADMIN ]; then

	/var/asl/data/templates/template-cpanel-apache-hook | tee -a $LOG

  fi

  cd /root


  if [ ! -d /etc/httpd/conf.d ]; then
    mkdir /etc/httpd/conf.d
    touch /etc/httpd/conf.d/00_mod_security.conf
  fi
  if [ ! -d /etc/httpd/modsecurity.d ]; then
    mkdir /etc/httpd/modsecurity.d
    touch /etc/httpd/modsecurity.d//modsecurity_crs_10_config.conf
  fi


else 
	# Standard Installation starts here (Recommended)

	
	if [ "$DIST" == "el7" ]; then
		# httpd 2.4 includes mod_sed natively
		yum -y install asl psmon mod_security mod_evasive | tee -a $LOG
	else
		yum -y install asl psmon mod_security mod_evasive mod_sed | tee -a $LOG
	fi
        if [ ${PIPESTATUS[0]} -ge 1 ]; then
                        echo
                        echo "Error: Could not install ASL" |tee -a $LOG
                        exit 1
        fi


fi


post_asl_install | tee -a $LOG

echo "Installation completed" >> $LOG

