#!/bin/bash
#################################################################
# auto-mediawiki						#
# Instala un servidor LAMP (Linux+Apache+MySQL+PHP) e instala	#
# MediaWiki y lo configura.					#
#								#
# Guzman Castanedo Villalba (guzman@castanedo.es) Junio 2018	#
# GPLv3 (https://www.gnu.org/licenses/gpl.html)			#
#################################################################

comprobarError() {
	# Mejora: tratar todos los mensajes de error desde aquí
	printf "SIN HACER...\n"
}

OSInfo() {
	#printf "Detectando SO..."
	OS=$(uname -s)
	if [ $OS = "Linux" ]; then
		OS="GNU/Linux"
		if [ -f /etc/os-release ]; then
			DIST=$(grep ^NAME= /etc/os-release | cut -d = -f 2 | cut -d '"' -f 2)
			REV=$(grep ^VERSION= /etc/os-release | cut -d = -f 2 | cut -d '"' -f 2)
			ID_LIKE=$(grep ^ID_LIKE= /etc/os-release | cut -d = -f 2 | cut -d '"' -f 2)
			for i in $ID_LIKE; do
				#printf "$i\n"
				case $i in
					debian|ubuntu)
						debianOS=true
						break
						;;
					rhel|fedora)
						rhelOS=true
						break
						;;
					*)
						debianOS=false
						rhelOS=false
						;;
				esac
			done
		elif [ -f /etc/debian-version ]; then
			# Familia Debian (Debian, Ubuntu, Linux Mint, ...)
			DIST="Debian"
			REV=""
			ID_LIKE="debian"
			debianOS=true
		elif [ -f /etc/redhat-release ]; then
			# Familia Red-Hat (RHEL, Fedora, CentOS, ...)
			DIST="Red-Hat"
			REV=""
			ID_LIKE="rhel"
			rhelOS=true
		else
			# Other Linux (No Soportado)
			DIST=""
			REV=""
			ID_LIKE=""
		fi
	else
		# UNIX, OS X, ... (No Soportado)
		DIST=$OS
		REV=""
	fi
	#printf " $OS $DIST $REV\n"
	HDInfo=$(df -h | head -1)"\n"$(df -h | grep ^/dev/sd)"\n"$(df -h | grep ^/dev/mapper)
}

comprobarRoot() {
	if [ $(id -u) -ne 0 ]; then
		printf "ERROR:\tEs necesario ser root ('sudo $0').\n"
		exit 1
	fi
}

comprobarDependencias() {
	# Comprobamos whiptail
	which whiptail > /dev/null 2>&1
	if [ $? -ne 0 ];then
		printf "ERROR:\t'whiptail' no disponible.\n"
		exit 1
	fi
	# Comprobamos hostnamectl
	which hostnamectl > /dev/null 2>&1
	if [ $? -ne 0 ];then
		printf "ERROR:\t'hostnamectl' no disponible.\n"
		exit 1
	fi
	if [ $debianOS = true ];then
		# Comprobamos apt-get
		which apt-get > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			printf "ERROR:\t'apt-get' no está disponible.\n"
			exit 1
		fi
		# Actualizamos base de datos del repositorio
		printf "Actualizando repositorio APT..."
		result=$(apt-get -q -y update)
		if [ $? -ne 0 ]; then
			printf "\nERROR:\tImposible actualizar repositorio.\n"
			printf "Detalles:\n$result\n"
			exit 1
		fi
		printf " OK.\n"
		# Comprobamos Firewall (ufw)
		which ufw > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			printf "ERROR:\t'ufw' no disponible.\n"
			exit 1
		fi
	fi
	if [ $rhelOS = true ]; then
		# Comprobamos yum
		which yum > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			printf "ERROR:\t'yum' no está disponible.\n"
			exit 1
		fi
		# Actualizamos base de datos del repositorio
		printf "Actualizando repositorio YUM..."
		result=$(yum -y makecache 2>&1)
		if [ $? -ne 0 ]; then
			printf "\nERROR:\tImposible actualizar repositorio.\n"
			printf "Detalles:\n$result\n"
			exit 1
		fi
		printf " OK.\n"
		# Comprobamos Firewall (firewall-cmd)
		which firewall-cmd > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			printf "ERROR:\t'firewall-cmd' no disponible.\n"
			exit 1
		fi
	fi
}

inicializarVariables() {
	debianOS=false
	rhelOS=false
	apacheOn=false
	nginxOn=false
	mySQLOn=false
	mariaDBOn=false
	phpOn=false
	mediaWikiOn=false
	moodleOn=false
	actualizacionesOn=false
}

instalacionExpress() {
	apacheOn=true
	mariaDBOn=true
	phpOn=true
	mediaWikiOn=true
	moodleOn=true
	actualizacionesOn=true
}

mostrarBienvenida() {
	if [ $debianOS = false ] && [ $rhelOS = false ]; then
		whiptail --title "ERROR S.O. NO SOPORTADO" --msgbox "Este script automatiza la creación de una web MediaWiki SOLO para distribuciones Linux de la familia Debian (Ubuntu, Linux Mint, ...) y de la familia Red-Hat (CentOS, Fedora, ...).\n\nInformación del sistema:\nOS: $OS $DIST $REV\n$HDInfo" 20 70 --ok-button "Salir"
		exit 1
	fi
	whiptail --title "INSTALACION MEDIAWIKI" --yesno "Este script automatiza completamente la instalación de una wiki.\nPara ello instala un servidor LAMP, el software MediaWiki y lo configura todo.\n\nInformación del sistema:\nOS: $OS $DIST $REV\n$HDInfo" 20 70 --yes-button "Continuar" --no-button "Salir"
	if [ $? -ne 0 ]; then
		printf "ERROR:\tInstalación interrumpida por el usuario.\n"
		exit 2
	fi
}

mostrarExpress() {
	express=$(whiptail --title "INSTALACION EXPRESS" --radiolist "<ESPACIO>: seleccionar   <TAB>: cambiar   <FLECHAS>: moverse\n\nLa instalación express instala Apache2, MariaDB, PHP-7, Let's Encrypt, MediaWiki, Moodle y actualizaciones automáticas.\nSeleccione el tipo de instalación que desee:" 20 70 2 \
	"Express" "Instalación rápida" ON \
	"Avanzada" "Permite escoger todas las opciones disponibles" OFF \
	--ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3)
	if [ $? -ne 0 ]; then
		printf "ERROR:\tInstalación interrumpida por el usuario.\n"
		exit 2
	fi
	case $express in
		Express)
			instalacionExpress
			# DECIDIR QUÉ OPCIONES SON LAS MÍNIMAS
			;;
		Avanzada)
			mostrarAvanzada
			;;
		*)
			printf "ERROR:\tError interno (selección express).\n"
			exit 1
			;;
	esac
}

mostrarAvanzada() {
	componentes=$(whiptail --title "INSTALACION AVANZADA" --checklist "<ESPACIO>: seleccionar   <TAB>: cambiar   <FLECHAS>: moverse\n\nEscoge los componentes que quieres instalar:" 20 70 7 \
	"WebServer" "Instalar servidor web http/https" ON \
	"Database" "Instalar una base de datos SQL" ON \
	"PHP" "Instala PHP7" ON \
	"SSL/TLS" "Instalar certificados para activar HTTPS" ON \
	"MediaWiki" "Instalar wiki con MediaWiki" ON \
	"Moodle" "Instalar campus virtual con Moodle" ON \
	"Actualizaciones" "Programar actualizaciones automáticas" ON \
	--ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3)
	if [ $? -ne 0 ]; then
		printf "ERROR:\tInstalación interrumpida por el usuario.\n"
		exit 2
	fi
	# Mejora: autodetección de componentes ya instalados
	for i in $componentes; do
		case $i in
			\"WebServer\")
				mostrarWebServer
				;;
			\"Database\")
				mostrarDatabase
				;;
			\"PHP\")
				phpOn=true
				;;
			\"SSL/TLS\")
				# 2 Opciones: Let's Encrypt o Autofirmado
				;;
			\"MediaWiki\")
				mediaWikiOn=true
				;;
			\"Moodle\")
				moodleOn=true
				;;
			\"Actualizaciones\")
				actualizacionesOn=true
				;;
			*)
				printf "ERROR:\tError interno (selección de componentes).\n"
				exit 1
				;;
		esac
	done
}

mostrarWebServer() {
	webServer=$(whiptail --title "SERVIDOR WEB" --radiolist "<ESPACIO>: seleccionar   <TAB>: cambiar   <FLECHAS>: moverse\n\nEscoge el servidor web que quieres usar:" 20 70 2 \
	"Apache" "Instalar el servidor web Apache2" ON \
	"Nginx" "Instalar el servidor web Nginx" OFF \
	--ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3)
	if [ $? -ne 0 ]; then
		printf "ERROR:\tInstalación interrumpida por el usuario.\n"
		exit 2
	fi
	case $webServer in
		Apache)
			apacheOn=true
			;;
		Nginx)
			nginxOn=true
			;;
		*)
			printf "ERROR:\tError interno (selección de web server).\n"
			exit 1
			;;
	esac
	# Otras opciones (FQDN)
	establecerFQDN
}

establecerFQDN() {
	while [ -z $hostname ]; do
		hostname=$(whiptail --title "FQDN" --inputbox "El nombre de dominio principal (FQDN) de este servidor es:\n"$(hostname)"\n\nQuieres cambiarlo por otro?" 20 70 --ok-button "Cambiar" --cancel-button "No Cambiar" 3>&1 1>&2 2>&3)
		if [ $? -eq 0 ] && [ ! -z $hostname ]; then
			hostnamectl set-hostname $hostname
		else
			hostname=$(hostname)
		fi
	done
	#printf "\nHostname: $hostname\n"
}

instalarApache() {
	if [ $debianOS = true ];then
		result=$(apt-get -q -y install apache2 2>&1)
		if [ $? -ne 0 ]; then
			printf "\nERROR:\tError al instalar Apache2.\n"
			printf "Detalles:\n$result\n"
			exit 1
		fi
	elif [ $rhelOS = true ]; then
		result=$(yum -y install httpd 2>&1)
		if [ $? -ne 0 ]; then
			printf "\nERROR:\tError al instalar Apache2.\n"
			printf "Detalles:\n$result\n"
			exit 1
		fi
	else
		printf "\nERROR:\tError interno (instalación Apache2).\n"
		exit 1
	fi
}

instalarNginx() {
	if [ $debianOS = true ];then
		result=$(apt-get -q -y install nginx 2>&1)
		if [ $? -ne 0 ]; then
			printf "\nERROR:\tError al instalar Nginx.\n"
			printf "Detalles:\n$result\n"
			exit 1
		fi
	elif [ $rhelOS = true ]; then
		# Hay que instalar primero otro repositorio
		result=$(yum -y install epel-release)
		if [ $? -ne 0 ]; then
			printf "\nERROR:\tError al intalar repositorio 'epel-release'.\n"
			printf "Detalles:\n$result\n"
			exit 1
		fi
		result=$(yum -y install nginx 2>&1)
		if [ $? -ne 0 ]; then
			printf "\nERROR:\tError al instalar Nginx.\n"
			printf "Detalles:\n$result\n"
			exit 1
		fi
	else
		printf "\nERROR:\tError interno (instalación Nginx).\n"
		exit 1
	fi
}

mostrarDatabase() {
	if [ $debianOS = true ]; then
		database=$(whiptail --title "BASE DE DATOS" --radiolist "<ESPACIO>: seleccionar   <TAB>: cambiar   <FLECHAS>: moverse\n\nEscoge la base de datos que quieres usar:" 20 70 2 \
		"MySQL" "Instalar la base de datos MySQL (no uso comercial)" ON \
		"MariaDB" "Instalar la base de datos MariaDB (fork de MySQL)" OFF \
		--ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3)
		if [ $? -ne 0 ]; then
			printf "ERROR:\tInstalación interrumpida por el usuario.\n"
			exit 2
		fi
		case $database in
			MySQL)
				mySQLOn=true
				;;
			MariaDB)
				mariaDBOn=true
				;;
			*)
				printf "ERROR:\tError interno (selección de base de datos).\n"
				exit 1
				;;
		esac
	elif [ $rhelOS = true ]; then
		whiptail --title "BASE DE DATOS" --yesno "Para su distribucion $OS $DIST $REV, sólo está disponible la base de datos MariaDB." 20 70 --yes-button "Continuar" --no-button "Salir"
		if [ $? -ne 0 ]; then
			printf "ERROR:\tInstalación interrumpida por el usuario.\n"
			exit 2
		fi
		mariaDBOn=true
	else
		printf "ERROR:\tError interno (instalación Base de Datos).\n"
		exit 1
	fi
	# Otras opciones (contraseña)
	leerSQLPasswd
}

leerSQLPasswd() {
	control=false
	error=""
	# Leemos la contreseña (stdin) y confirmamos
	while [ $control = false ]; do
		sqlPasswd=$(whiptail --title "CONTRASEÑA SQL" --passwordbox "$error""Introduzca la contraseña para el usuario 'root' de la base de datos:" 20 70 --ok-button "Continuar" --nocancel 3>&1 1>&2 2>&3)
		if [ $? -ne 0 ]; then
			printf "ERROR:\tInstalación interrumpida por el usuario.\n"
			exit 2
		fi
		sqlPasswd2=$(whiptail --title "CONTRASEÑA SQL" --passwordbox "Confirme la contraseña:" 20 70 --ok-button "Continuar" --nocancel 3>&1 1>&2 2>&3)
		if [ $? -ne 0 ];then
			printf "ERROR:\tInstalación interrumpida por el usuario.\n"
			exit 2
		fi
		#printf "SQL Password 1: $sqlPasswd\n"
		#printf "SQL Password 2: $sqlPasswd2\n"
		if [ -z $sqlPasswd ] || [ -z $sqlPasswd2 ]; then
			error="ERROR: LA CONTRASEÑA NO PUEDE ESTAR VACIA.\n"
		elif [ $sqlPasswd != $sqlPasswd2 ];then
			error="ERROR: LAS CONTRASEÑAS NO COINCIDEN.\n"
		else
			control=true
		fi
	done
	#printf "SQL Password: $sqlPasswd\n"
	unset control error sqlPasswd2
}

establecerSQLPasswd() {
	# Establecemos SQL root passwd y securizamos BD (mysql_secure_installation)
	# FALTA REDIRIFIR LA SALIDA ESTÁNDAR
	mysql -e "FLUSH PRIVILEGES"
	if [ $? -eq 0 ];then
		# Establecemos contraseña del usuario root
		mysql -e "UPDATE mysql.user SET Password = PASSWORD('$sqlPasswd') WHERE User = 'root'"
		if [ $? -ne 0 ];then
			printf "SQL ERROR:\tImposible de cambiar la contraseña de 'root'.\n"
			exit 3
		fi
		# Desactivamos acceso root desde el exterior (solo localhost)
		mysql -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1')"
		if [ $? -ne 0 ];then
			printf "SQL ERROR:\tImposible desactivar acceso 'root' desde el exterior.\n"
			exit 3
		fi
		# Eliminamos todos los usuarios anónimos
		mysql -e "DELETE FROM mysql.user WHERE User=''"
		if [ $? -ne 0 ];then
			printf "SQL ERROR:\tImposible eliminar usuarios anónimos.\n"
			exit 3
		fi
		# Eliminamos bases de datos 'test'
		mysql -e "DROP DATABASE IF EXISTS test"
		if [ $? -ne 0 ];then
			printf "SQL WARNING:\tImposible eliminar bases de datos de pruebas.\n"
		fi
		# Eliminamos privilegios de la base de datos 'test'
		mysql -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'"
		if [ $? -ne 0 ];then
			printf "SQL WARNING:\tImposible eliminar los privilegios de la base de datos de pruebas.\n"
		fi
		# Aplicamos los cambios
		mysql -e "FLUSH PRIVILEGES"
		if [ $? -ne 0 ];then
			printf "SQL ERROR:\tImposible recargar base de datos.\n"
			exit 3
		fi
	else
		printf "WARNING:\tUsuario 'root' ya dispone de contraseña.\n"
	fi
}

instalarMySQL() {
	if [ $debianOS = true ];then
		result=$(apt-get -q -y install mysql-server mysql-client 2>&1)
		if [ $? -ne 0 ]; then
			printf "\nERROR:\tError al instalar MySQL.\n"
			printf "Detalles:\n$result\n"
			exit 1
		fi
	elif [ $rhelOS = true ]; then
		# MySQL no disponible en RHEL. 2 opciones:
		# 1) Instalar un repositorio adicional
		# 2) No instalar MySQL en distribuciones RHEL
		printf "\nERROR:\tRHEL no incluye MySQL en sus repositorios.\n"
		exit 1
	else
		printf "\nERROR:\tError interno (instalación MySQL).\n"
		exit 1
	fi
}

instalarMariaDB() {
	if [ $debianOS = true ];then
		result=$(apt-get -q -y install mariadb-server mariadb-client 2>&1)
		if [ $? -ne 0 ]; then
			printf "\nERROR:\tError al instalar MariaDB.\n"
			printf "Detalles:\n$result\n"
			exit 1
		fi
	elif [ $rhelOS = true ]; then
		result=$(yum -y install mariadb-server mariadb 2>&1)
		if [ $? -ne 0 ]; then
			printf "\nERROR:\tError al instalar MariaDB.\n"
			printf "Detalles:\n$result\n"
			exit 1
		fi
	else
		printf "\nERROR:\tError interno (instalación MariaDB).\n"
		exit 1
	fi
}

# Comprobación del sistema e inicialización
comprobarRoot
inicializarVariables
OSInfo
comprobarDependencias

# Bienvenida
mostrarBienvenida
# Selección de componentes (express vs avanzada)
mostrarExpress

# Pre-configuración
	# Habilitar cortafuegos -> PROBLEMA: se corta la conexión ssh
	
# Instalación
	# FALTA: whiptail --gauge -> Más bonito
	# Servidor Web
	if [ $apacheOn = true ]; then
		printf "Instalando Web Server Apache..."
		instalarApache
		printf " OK.\n"
	elif [ $nginxOn = true ]; then
		printf "Instalando Web Server Nginx..."
		instalarNginx
		printf " OK.\n"
	fi
	# Base de Datos
	if [ $mySQLOn = true ]; then
		printf "Instalando Base de Datos MySQL..."
		instalarMySQL
		printf " OK.\n"
	elif [ $mariaDBOn = true ]; then
		printf "Instalando Base de Datos MariaDB..."
		instalarMariaDB
		printf " OK.\n"
	fi
	# PHP
	if [ $phpOn = true ]; then
		printf "Instalando PHP-7..."
		printf " OK.\n"
	fi
	# SSL/TLS
		# Falta por implementar
	# MediaWiki
	if [ $mediaWikiOn = true ]; then
		printf "Instalando MediaWiki..."
		printf " OK.\n"
	fi
	# Moodle
	if [ $moodleOn = true ]; then
		printf "Instalando Moodle..."
		printf " OK.\n"
	fi	
	
# PRECAUCION!!!! Hay que habilitar algunos servicios antes de configurarlos
# Por ejemplo: para cambiar la contraseña de root en mysql

# Configuración
	# Configuración Apache
		# Virtual Hosts
	# Configuración Database
		# Establecer Contrasñea y configuración Segura
		if [ $mySQLOn = true ] || [ $mariaDBOn = true ];then
			establecerSQLPasswd
		fi
	# Configuración PHP
		# cgi.fix_pathinfo=0
		# Configurar máximo de subida de archivos
	# Configuración MediWiki
	# Configuración Moodle
	# Arrancar y habilitar todos los servicios (SystemD, Service o SystemV)
	# Añadir reglas del cortafuegos
	# Configuración SSL/TLS
		# Generar certificados
		# Configurar certificados
	# Configurar actualizaciones
	if [ $actualizacionesOn = true ]; then
		printf "Configurando actualizaciones automáticas..."
		# CRONTAB
		printf " OK.\n"
	fi

# Autodestrucción
{
	for i in $(seq 0 5 50); do
		sleep 0.1
		echo $i
	done
} | whiptail --gauge "Autodestrucción..." 7 70 0
{
	for i in $(seq 50 5 100); do
		sleep 0.1
		echo $i
	done
} | whiptail --gauge "Autopulverización..." 7 70 50