#!/usr/bin/bash

if [ $(whoami) != "root" ]; then
	echo "ERROR: must be run as root or with sudo as root"
	exit 1
fi

if [ "$1" != "force-this" ]; then
	echo "This program will 'take over' the web"
	echo "configuration of this host so that Firefly Logger"
	echo "is running as the primary/only website. Only"
	echo "run this if this server is not otherwise configured"
	echo "for any other website!!"
	echo ""
	echo "ANY OTHER APACHE2 OR WEBSITE DATA WILL BE DESTROYED!"
	echo ""
	read -p "DO YOU WANT TO CONTINUE (Y/N)??  " answer
	case ${answer:0:1} in
		y|Y)
		;;
	
		*)
			exit 0
		;;
	esac
fi

systemctl enable apache2
systemctl start apache2
systemctl enable mariadb
systemctl start mariadb
a2enmod ssl
a2ensite default-ssl

cat - > /etc/apache2/sites-available/000-default.conf <<EOF
<VirtualHost *:80>
  ServerAdmin webmaster@firefly-logger
  DocumentRoot /var/www/html

  ErrorLog \${APACHE_LOG_DIR}/error.log
  CustomLog \${APACHE_LOG_DIR}/access.log combined

  RewriteEngine On
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP_HOST} !^(localhost|127\.0\.0\.1|\[?::1\]?)$ [NC]
  RewriteRule ^.* https://%{HTTP_HOST}%{REQUEST_URI} [R,L,QSA]
</VirtualHost>
EOF

cat - > /etc/apache2/sites-available/default-ssl.conf <<EOF
<VirtualHost *:443>
        ServerAdmin webmaster@firefly-logger
        DocumentRoot /var/www/html

        ErrorLog \${APACHE_LOG_DIR}/error.log
        CustomLog \${APACHE_LOG_DIR}/access.log combined

        SSLEngine on
        SSLCertificateFile      /etc/ssl/certs/ssl-cert-snakeoil.pem
        SSLCertificateKeyFile   /etc/ssl/private/ssl-cert-snakeoil.key

        <FilesMatch "\.(?:cgi|shtml|phtml|php)$">
                SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
                SSLOptions +StdEnvVars
        </Directory>

</VirtualHost>
EOF

cat - > /var/www/html/index.html <<EOF
<meta http-equiv="refresh" content="0; url=/firefly-logger/index.html" />
EOF

systemctl restart apache2
