#!/bin/sh
#
# metadata_begin
# recipe: WordPress
# tags: centos7
# revision: 2
# description_ru: LAMP + Nginx + WordPress. Пароль для MySQL можно найти в /root/.my.cnf . Для базы wordpress в /root/.wp.cnf
# description_en: LAMP + Nginx + WordPress. Password for MySQL might be found in /root/.my.cnf . For wordpress database in  /root/.wp.cnf
# metadata_end
#

set -x

LOG_PIPE=/tmp/log.pipe.$$                                                                                                                                                                                                                    
mkfifo ${LOG_PIPE}
LOG_FILE=/root/lamp.log
touch ${LOG_FILE}
chmod 600 ${LOG_FILE}

tee < ${LOG_PIPE} ${LOG_FILE} &

exec > ${LOG_PIPE}
exec 2> ${LOG_PIPE}

killjobs() {
	test -n "$(jobs -p)" && kill $(jobs -p) || :
}
trap killjobs INT TERM EXIT

echo
echo "=== Recipe LAMP started at $(date) ==="
echo

if [ -f /etc/redhat-release ]; then
	OSNAME=centos
else
	OSNAME=debian
fi

RootMyCnf() {
	# Saving mysql password
	touch /root/.my.cnf 
	chmod 600 /root/.my.cnf
	echo "[client]" > /root/.my.cnf
	echo "password=${1}" >> /root/.my.cnf

}
WordPressMyCnf() {
	# Saving mysql password
	touch /root/.wp.cnf 
	chmod 600 /root/.wp.cnf
	echo "[client]" > /root/.wp.cnf
	echo "password=${1}" >> /root/.wp.cnf

}

if [ "${OSNAME}" = "debian" ]; then
	export DEBIAN_FRONTEND="noninteractive"
	apt-get update
	which which 2>/dev/null || apt-get -y install which
	which lsb-release 2>/dev/null || apt-get -y install lsb-release
	which logger 2>/dev/null || apt-get -y install bsdutils
	pkglist="vim apache2 nginx"
	if ! dpkg -s mysql-server >/dev/null 2>/dev/null; then
		install_mysql=yes
		pkglist="${pkglist} mysql-server"
	fi
	if ! dpkg -s phpmyadmin >/dev/null 2>/dev/null; then
		install_phpmyadmin=yes
		pkglist="${pkglist} phpmyadmin"
		echo "phpmyadmin      phpmyadmin/reconfigure-webserver        multiselect     apache2" | debconf-set-selections
	fi
	if [ "$(lsb_relese -s -c)" = "xenial" ]; then
		pkglist="${pkglist} libapache2-mod-php php-cli"
	else
		pkglist="${pkglist} libapache2-mod-php5 php5-cli"
	fi

	
	if [ -n "($PASS)" ] && [ "($PASS)" != "()" ]; then
		mysqlpass="($PASS)"
	else
		apt-get -y install pwgen
		mysqlpass=$(pwgen -s 10 1)
	fi

	if [ -n "${install_mysql}" ]; then
		# Setting mysql root password
		echo "mysql-server mysql-server/root_password password ${mysqlpass}" | debconf-set-selections
		echo "mysql-server mysql-server/root_password_again password ${mysqlpass}" | debconf-set-selections
	fi
	
	# Installing packages
	apt-get -y install ${pkglist}

	if [ -n "${install_mysql}" ] && [ ! -e /root/.my.cnf ]; then
		RootMyCnf ${mysqlpass}
	fi

	if [ -f /etc/nginx/sites-enabled/default ]; then
		rm -f /etc/nginx/sites-enabled/default
		apt-get -f install
	fi
else
	OSREL=$(rpm -qf --qf '%{version}' /etc/redhat-release)

	# Setting proxy
	if [ ! "($HTTPPROXYv4)" = "()" ]; then
		# Стрипаем пробелы, если они есть
		PR=($HTTPPROXYv4)
		PR=$(echo ${PR} | sed "s/''//g" | sed 's/""//g')
		if [ -n "${PR}" ]; then
			echo "proxy=${PR}" >> /etc/yum.conf
			#export http_proxy="${PR}"
			#export HTTP_PROXY="${PR}"
		fi
	fi


	Service() {
		# $1 - name
		# $2 - command

		if [ -f /usr/bin/systemctl ]; then
			systemctl ${2} ${1}.service
		else
			if [ "${2}" = "enable" ]; then
				chkconfig ${1} on
			else
				service ${1} ${2}
			fi
		fi
	}

	yum -y install epel-release


	# nginx repo
	cat > /etc/yum.repos.d/nginx.repo << EOF

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/${OSREL}/\$basearch/
gpgcheck=0
enabled=1
EOF
	
	pkglist="vim nginx httpd php phpmyadmin"
	if [ ${OSREL} -ge 7 ]; then
		pkglist="${pkglist} mariadb-server"
		mysqlname=mariadb
	else
		pkglist="${pkglist} mysql-server"
		mysqlname=mysqld
	fi
	yum -y install ${pkglist} || yum -y install ${pkglist} || yum -y install ${pkglist}

	if [ -f /etc/httpd/conf.d/phpMyAdmin.conf ]; then
		cat > /tmp/sed.$$ << EOF
/<Directory \/usr\/share\/phpMyAdmin\/>/,/<\/Directory>/ {
    /<RequireAny>/,/<\/RequireAny>/d;
    /<IfModule !mod_authz_core.c>/,/<\/IfModule>/s/Deny from All/Allow from All/g;
    /<IfModule mod_authz_core.c>/a\\\tRequire all granted 
};
/<Directory \/usr\/share\/phpMyAdmin\/setup\/>/,/<\/Directory>/ {
    /<IfModule mod_authz_core.c>/a\\\tRequire all denied
    /<RequireAny>/,/<\/RequireAny>/d;
    /<IfModule !mod_authz_core.c>/,/<\/IfModule>/{ /Allow from/d}
}
EOF
		sed -i -r -f /tmp/sed.$$ /etc/httpd/conf.d/phpMyAdmin.conf
	fi

	test -f /etc/nginx/conf.d/default.conf && rm -f /etc/nginx/conf.d/default.conf

	Service httpd enable
	Service httpd start
	Service nginx enable
	Service nginx start
	Service ${mysqlname} enable

	if [ -z "$(ls /var/lib/mysql/)" ]; then
		install_mysql=yes
	fi
	Service ${mysqlname} start

        if [ -n "${install_mysql}" ];
                #then
                # Setting mysql password
                #if [ -n "($PASS)" ] && [ "($PASS)" != "()" ]; then
                #       mysqlpass="($PASS)"
                then
                        rpm -q pwgen || yum -y install pwgen
                        mysqlpass=$(pwgen -s 10 1)
                fi
                RootMyCnf ${mysqlpass}
                /usr/bin/mysql -u root --password= -e "FLUSH PRIVILEGES;"
                /usr/bin/mysql -u root --password= -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('$mysqlpass');"
                
        fi

	# Removing proxy
	sed -r -i "/proxy=/d" /etc/yum.conf
	firewall-cmd --zone=public --permanent --add-service=http
    service firewalld restart

mysqlpass_wp=$(pwgen -s 10 1)
WordPressMyCnf ${mysqlpass_wp}
/usr/bin/mysql -u root --password=$mysqlpass << EOF
        CREATE DATABASE wordpress;
        CREATE USER wordpressuser@localhost IDENTIFIED BY '$mysqlpass_wp';
        GRANT ALL PRIVILEGES ON wordpress.* TO wordpressuser@localhost IDENTIFIED BY '$mysqlpass_wp';
        FLUSH PRIVILEGES;
        exit
EOF
yum -y install php-gd, rsync
service httpd restart
cd ~
wget http://wordpress.org/latest.tar.gz
tar xzvf latest.tar.gz
rsync -avP ~/wordpress/ /var/www/html/
mkdir /var/www/html/wp-content/uploads
chown -R apache:apache /var/www/html/*
cd /var/www/html
#cp wp-config-sample.php wp-config.php
cat <<EOT > wp-config.php
<?php
/**
 * The base configuration for WordPress
 *
 * The wp-config.php creation script uses this file during the
 * installation. You don't have to use the web site, you can
 * copy this file to "wp-config.php" and fill in the values.
 *
 * This file contains the following configurations:
 *
 * * MySQL settings
 * * Secret keys
 * * Database table prefix
 * * ABSPATH
 *
 * @link https://codex.wordpress.org/Editing_wp-config.php
 *
 * @package WordPress
 */

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'wordpress');

/** MySQL database username */
define('DB_USER', 'wordpressuser');

/** MySQL database password */
define('DB_PASSWORD', '$mysqlpass_wp');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

/**#@+
 * Authentication Unique Keys and Salts.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define('AUTH_KEY',         'put your unique phrase here');
define('SECURE_AUTH_KEY',  'put your unique phrase here');
define('LOGGED_IN_KEY',    'put your unique phrase here');
define('NONCE_KEY',        'put your unique phrase here');
define('AUTH_SALT',        'put your unique phrase here');
define('SECURE_AUTH_SALT', 'put your unique phrase here');
define('LOGGED_IN_SALT',   'put your unique phrase here');
define('NONCE_SALT',       'put your unique phrase here');

/**#@-*/

/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each
 * a unique prefix. Only numbers, letters, and underscores please!
 */
EOT
        echo '$table_prefix = '"'"'wp_'"'"';' >> wp-config.php

        cat <<EOT >> wp-config.php
/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 *
 * For information on other constants that can be used for debugging,
 * visit the Codex.
 *
 * @link https://codex.wordpress.org/Debugging_in_WordPress
 */
define('WP_DEBUG', false);

/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
        define('ABSPATH', dirname(__FILE__) . '/');

/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
EOT
rm /root/lamp.log

