#!/bin/bash

###############################################

NUMBER_OF_SITES=100
DIRNAME="/var/www/vhosts"
ROOTPASSWD="test"
MYSQLHOST="127.0.0.1"
MYUSER="root"
DEPLOY_TYPE=0
NEED_DEPLOY="n"

ERROR=1
OK=0

OPTIND=1
debug="debug"

testuser="test10005"
testhost="testhost"
testhost_sql="wtest10006"

confdir="./"

###############################################
function showMessage {
    if [ -n "$debug" ]; then
        if [ -n "$2" ]; then
            echo "$1"
        else
            echo -n "$1"
        fi
    fi
}

function showMessageNoDebug {
    if [ -n "$2" ]; then
        echo "$1"
    else
        echo -n "$1"
    fi
}                                                        

checkProgram(){
    if [ -z "$1" ]; then
	echo ""
	return
    fi
    which "$1" 2>/dev/null | while read path;
    do
	if [ -n "$path" ]; then
	    result=$(echo "$path" | grep bin);
	    if [ -n "$result" ]; then
		echo "$result"
		return
	    fi
	fi
    done 
    echo ""
}
checkForUser(){
    if [ -z "$1" ]; then
	return 1
    fi
    result=$(cat /etc/passwd | grep "$1")
    if [ -z "$result" ]; then
	return 1
    else
	return 0
    fi
}
callMySQL(){
    RETVAL=0;
    if [ -z "$2" ]; then
	echo "use test\n; select 1;\n" > tmp.sql
    else
	echo "$2" > tmp.sql
    fi
    if [ "$MYUSER" != "127.0.0.1" ];then
	"$1" -Bn --skip-column-names --default-character-set=utf8 &>/dev/null < tmp.sql 
    else
	"$1" -Bn --skip-column-names --default-character-set=utf8 -h$MYSQLHOST -u$MYUSER --password=$ROOTPASSWD &>/dev/null < tmp.sql
    fi
    RETVAL=$?
    rm -f tmp.sql
    return $RETVAL
}
transformData(){
    if [ -z "$4" ];then
	cat "$1" | sed "s/$2/$3/ig"
    else
	cat "$1" | sed "s/$2/$3/ig" > $4
    fi
}
getCurrentIp(){
    ip=$(ifconfig eth0 | grep inet | awk '{print $2}' | sed 's/addr://' | sed '/^$/d' | sed 's/[ ]\*//g')
    if [ -z "$ip" ];then
	echo "127.0.0.1"
    else
	echo "$ip"
    fi
}
clearConfD(){
    if [ -e /etc/httpd/conf.d ];then
	rm -f /etc/httpd/conf.d/*.conf
    else
	mkdir -p /etc/httpd/conf.d
    fi
}

###############################################
curuser=$(whoami)
if [ "$curuser" != "root" ]; then
    showMessageNoDebug "Script must run under root..."
    exit $ERROR
fi

while getopts :n:d:p:s:u:c:hy Option;
do
  case $Option in
     h ) 
	showMessageNoDebug "###############################################" "NEWLINE"
	showMessageNoDebug "# test sites deployer for classic Apache conf #" "NEWLINE"
	showMessageNoDebug "# input params:                               #" "NEWLINE"
	showMessageNoDebug "# -n - number of sites                        #" "NEWLINE"
	showMessageNoDebug "# -d - dirname for sites                      #" "NEWLINE"
	showMessageNoDebug "# -p - root password for db access            #" "NEWLINE"
	showMessageNoDebug "# -s - mysql server address                   #" "NEWLINE"
	showMessageNoDebug "# -u - user				          #" "NEWLINE"
	showMessageNoDebug "# -c1 - deploy php as cgi(no mod_sucgid)      #" "NEWLINE"
	showMessageNoDebug "# -c2 - deploy php as cgi(mod_sucgid)         #" "NEWLINE" 
	showMessageNoDebug "# -y - deploy sites                           #" "NEWLINE"
	showMessageNoDebug "###############################################" "NEWLINE"
        
        exit $OK
     ;;
     n )
        NUMBER_OF_SITES=$OPTARG
     ;;
     d )
        DIRNAME=$OPTARG
     ;;
     p )
        ROOTPASSWD=$OPTARG
     ;;
     s )
        MYSQLHOST=$OPTARG
     ;;
     u )
        MYUSER=$OPTARG
     ;;
     c )
        DEPLOY_TYPE=$OPTARG
     ;;
     y )
        NEED_DEPLOY="y"
     ;;
     * )
        showMessageNoDebug "<script-name> -n <hosts number> -d <dir name> -p <password> -u <user name>" "NEWLINE"
        
        exit $ERROR
     ;;
  esac
done
shift $(($OPTIND - 1))

path_to_mysql=$(checkProgram "mysql")

if [ -z "$path_to_mysql" ]; then
    showMessageNoDebug "Mysql not found. Deploying aborted..."
    exit $ERROR
else
    callMySQL "$path_to_mysql"
    if [ $? != 0 ]; then
	showMessageNoDebug "Mysql connection error. Deploying aborted..."
	exit $ERROR
    else
	showMessage "mysql check ok..." "NEWLINE"
    fi
fi

checkForUser "apache"
if [ $? == 0 ];then
    apache_user="apache"
else
    apache_user="nobody"
fi

if [ "$NEED_DEPLOY" == "y" ];then

    CURRENTIP=$(getCurrentIp)
    CURRENTPORT=80

    if [ -e "/etc/httpd/conf/httpd.conf.bak" ];then
	BUF=""
    else
	mv /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.bak
    fi
    cp -f $confdir/httpd.conf /etc/httpd/conf

    if [ -e "/etc/httpd/vhosts" ];then
	rm -fr /etc/httpd/vhosts
	mkdir -p /etc/httpd/vhosts
    else
	mkdir -p /etc/httpd/vhosts
    fi

    cat /etc/httpd/conf/httpd.conf | sed "/NameVirtualHost $CURRENTIP:$CURRENTPORT/d" | sed "\$a\NameVirtualHost $CURRENTIP:$CURRENTPORT" > /etc/httpd/conf/httpd1.conf
    cat /etc/httpd/conf/httpd1.conf | sed '/Include \/etc\/httpd\/vhosts\//d' | sed '$a\Include /etc/httpd/vhosts/\*' > /etc/httpd/conf/httpd.conf
##############################################
    if [ -e "/tmp/site" ];then
	showMessage "Check path to site... Ok" "NEWLINE"
    else
	showMessage "Create path to site... "
	if [ -e "$confdir/site.tar.gz" ];then
	    rm -rf /tmp/site
	    tar -C /tmp -zxvf $confdir/site.tar.gz &>/dev/null
	else
	    showMessage "Failed" "NEWLINE"
	    exit $ERROR
	fi
	showMessage "Ok" "NEWLINE"
    fi

##############################################

    MIN_RANGE=10000
    let MAX_RANGE=$NUMBER_OF_SITES+$MIN_RANGE

    if [ -e "$DIRNAME" ];then
	rm -fr "$DIRNAME"
	mkdir -p "$DIRNAME"
	showMessage "Path $DIRNAME already exists... Ok" "NEWLINE"
    else
	mkdir -p "$DIRNAME"
	showMessage "Path $DIRNAME already created... Ok" "NEWLINE"
    fi
    for (( i=$MIN_RANGE; i<$MAX_RANGE; i++ ))
    do
	let INTERNAL=$i-$MIN_RANGE+1
	showMessage "Deploy site $INTERNAL from $NUMBER_OF_SITES..."
#Add user
	userName=$(cat /etc/passwd | grep "u$i")
	if [ -z "$userName" ]; then
	    useradd -d /dev/null -s /dev/null "u$i" &>/dev/null
	fi
    
#Sites structure created
	path_to_site="$DIRNAME/$i"
	rm -rf $path_to_site
	cp -r /tmp/site $path_to_site 2>/dev/null
	chown "u$i":"$apache_user" $path_to_site
	mkdir -p $path_to_site/log 
	chown "$apache_user" $path_to_site/log
	transformData "$path_to_site/webspace/httpdocs/wordpress/wp-config.php" "$testhost" "$MYSQLHOST" "$path_to_site/webspace/httpdocs/wordpress/wp-config1.php"
	transformData "$path_to_site/webspace/httpdocs/wordpress/wp-config1.php" "$testuser" "u$i" "$path_to_site/webspace/httpdocs/wordpress/wp-config.php"
	rm -f $path_to_site/webspace/httpdocs/wordpress/wp-config1.php
	chown "u$i":"$apache_user" -R $path_to_site/webspace
	chmod 770 -R $path_to_site/webspace
#DB structure created 
	result=$(transformData "$confdir/all.sql" "$testuser" "u$i")
	echo "$result" > /tmp/tmp.dt
	result=$(transformData "/tmp/tmp.dt" "$testhost_sql" "test$i")
	rm -f /tmp/tmp.dt
	callMySQL "$path_to_mysql" "$result"        
	if [ $? != 0 ]; then
    	    showMessageNoDebug "Mysql connection error. Deploying aborted - u$i..."
    	    exit $ERROR
	fi
    
#Apache conf modified
	usnm=$(id -u u$i)
	cat $confdir/vhost.conf | sed -e "s/SERVERIP/$CURRENTIP/g" -e "s/SERVERPORT/$CURRENTPORT/g" -e "s/UDIRNAME/$i/g" -e "s/HOSTNAME/test$i/g" -e "s/USERNAME/u$i/g" -e "s/USERID/$usnm/g"  > /etc/httpd/vhosts/"u$i".conf
    
	showMessage "Ok" "NEWLINE"
    done
    rm -rf /tmp/site
fi

#Apache Configure
case $DEPLOY_TYPE in
1 )
    showMessage "Configure with php as cgi and no mod_sucgid..."
    clearConfD
    cp $confdir/test_modcgi.conf /etc/httpd/conf.d
    cp $confdir/test_php_cgi.conf /etc/httpd/conf.d
    showMessage "Ok" "NEWLINE"
;;
2 )
    showMessage "Configure with php as cgi and with mod_sucgid..."
    clearConfD
    cp $confdir/test_modsucgid.conf /etc/httpd/conf.d
    cp $confdir/test_php_cgi.conf /etc/httpd/conf.d
    showMessage "Ok" "NEWLINE"
;;
3 )
    showMessage "Configure with php as cgi and with mod_sucgid but with NoLVE flag..."
    clearConfD
    cp $confdir/test_modsucgid_nolve.conf /etc/httpd/conf.d
    cp $confdir/test_php_cgi.conf /etc/httpd/conf.d
    showMessage "Ok" "NEWLINE"
;;
4 )
    showMessage "Configure with php as module and with mod_hostinglimits..."
    clearConfD
    cp $confdir/test_modhostinglimits.conf /etc/httpd/conf.d
    cp $confdir/test_php_mod.conf /etc/httpd/conf.d
    cp $confdir/test_modcgi.conf /etc/httpd/conf.d
    showMessage "Ok" "NEWLINE"
;;
0 )
    showMessage "No configure..." "NEWLINE"
;;
esac

service httpd restart
if [ $? != 0 ];then
    showMessageNoDebug "Apache restarting error..."
    exit $ERROR
fi

exit $OK