#!/usr/bin/bash
#
# Creates simple Apache/Nginx configurations for SmartOS VMs.
# Copyright (c) 2016 Joyent Inc., All rights reserved.

set -o errexit
set -o pipefail
#set -o nounset
#set -o xtrace

usage() {
cat <<-EOF >&2

Usage: $0 [options] TYPE DOMAINNAME DOCUMENTROOT

Arguments:
   
    TYPE             Nginx or Apache. 
    DOMAINNAME       The domain name or IP of the website.   eg: mywebsite.com
    DOCUMENTROOT     Directory of web server document root.  eg: /home/admin/web/public

Options:
   
    -p               PHP support (php passed to php-fpm).
    -r               Rails support (mod_passenger, apache only).
    -s               SSL support (insert your own certificates).
    -t               Tomcat support (proxy 8080 to localhost).

EOF
exit 1;
}

while getopts "prst" option; do
        case ${option} in
                p)
                        opt_p="true";
                        ;;
                r)
                        opt_r="true";
                        ;;
                s)
                        opt_s="true";
                        ;;
		t)
			opt_t="true";
			;;
                *)
                        usage;
                        ;;
        esac
done

fail() {
        printf "\n! $*\n\n" >&2;
        exit 1;
}

[[ ${opt_r} ]] && [[ "$2" = "nginx" ]] && fail "Nginx passenger support is not available yet.";
[[ ${opt_s} ]] && [[ ${opt_t} ]] && fail "You must specify -s or -t, not both.";
[[ ${opt_p} ]] && [[ ${opt_t} ]] && fail "You must specify -t or -p, not both.";
[[ ${opt_r} ]] && [[ ${opt_p} ]] && fail "You must specify -r or -p, not both.";
[[ ${opt_r} ]] && [[ ${opt_t} ]] && fail "You must specify -r or -t, not both.";
[[ ${opt_r} ]] && [[ ${opt_s} ]] && fail "You must specify -r or -s, not both.";

shift $(($OPTIND - 1))
if [[ $# = 3 ]]; then
        http_type=$1;
        http_host=$2;
        http_docroot=$3;
else
        usage;
fi


export LANG=C
PATH="/opt/local/bin:/opt/local/gnu/bin:/opt/local/sbin:/usr/bin:/usr/sbin";
#http_docroot_parent=$(echo ${http_docroot} | sed 's,/*[^/]\+/*$,,');
http_conffile="${http_host}.conf";
http_sslconffile="${http_host}-ssl.conf";
apache_confdir="/opt/local/etc/httpd";
nginx_confdir="/opt/local/etc/nginx";
apache_confdir_vhosts="/opt/local/etc/httpd/virtualhosts";
nginx_confdir_vhosts="/opt/local/etc/nginx/virtualhosts";
ip_external=$(ifconfig net0 | awk '/inet/ { print $2 }');

apache_create_config() {
	# Create first part of configuration
	cat > ${apache_confdir_vhosts}/${http_conffile} <<-EOF
	<VirtualHost *:80>
	  ServerName ${http_host}
	  ServerAlias www.${http_host}
	  ServerAlias *.${http_host}
	  DocumentRoot ${http_docroot}
	EOF

	# Create php part of configuration
	if [[ ${opt_p} ]]; then
		cat >> ${apache_confdir_vhosts}/${http_conffile} <<-EOF
		  DirectoryIndex index.html index.htm index.php
		  ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/home/admin/web/public/\$1
		EOF
	else
		cat >> ${apache_confdir_vhosts}/${http_conffile} <<-EOF
		  DirectoryIndex index.html index.htm index.php
		EOF
	fi

	# Create vhost part of configuration	
	cat >> ${apache_confdir_vhosts}/${http_conffile} <<-EOF
	  <Directory ${http_docroot}>
	    Options Indexes IncludesNOEXEC FollowSymLinks MultiViews
	    AllowOverride None
	    Require all granted
	  </Directory>
	EOF

	# Create tomcat part of configuration
	if [[ ${opt_t} ]]; then
		cat >> ${apache_confdir_vhosts}/${http_conffile} <<-EOF
		  ProxyPass /assets !
		  ProxyRequests Off
		  ProxyPreserveHost On
		  <Proxy *>
		    Order deny,allow
		    Allow from all
		  </Proxy>
		  ProxyPass / http://localhost:8080/
		  ProxyPassReverse / http://localhost:8080/
		EOF
	fi

	# Create end part of configuration
	cat >> ${apache_confdir_vhosts}/${http_conffile} <<-EOF
	</VirtualHost>
	EOF
}
apache_create_sslconfig() {
	# Create ssl configuration
	cat > ${apache_confdir_vhosts}/${http_sslconffile} <<-EOF
	<VirtualHost ${ip_external}:443>
	  ServerName ${http_host}
	  ServerAlias www.${http_host}
	  ServerAlias *.${http_host}
	  DocumentRoot ${http_docroot}
	EOF

	# Create php part of configuration
	if [[ ${opt_p} ]]; then
		cat >> ${apache_confdir_vhosts}/${http_sslconffile} <<-EOF
		  DirectoryIndex index.html index.htm index.php
		  ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/home/admin/web/public/\$1
		EOF
	else
		cat >> ${apache_confdir_vhosts}/${http_sslconffile} <<-EOF
		  DirectoryIndex index.html index.htm index.php
		EOF
	fi

	# Create vhost part of configuration	
	cat >> ${apache_confdir_vhosts}/${http_sslconffile} <<-EOF
	  <Directory ${http_docroot}>
	    Options Indexes IncludesNOEXEC FollowSymLinks MultiViews
	    AllowOverride None
	    Require all granted
	  </Directory>
	  SSLEngine on
	  SSLCertificateFile ${apache_confdir_vhosts}/${http_host}.crt
	  SSLCertificateKeyFile ${apache_confdir_vhosts}/${http_host}.key
	</VirtualHost>
	EOF
}
apache_create_railsconfig() {
	cat > ${apache_confdir_vhosts}/${http_conffile} <<-EOF
	<VirtualHost *:80>
	  ServerName ${http_host}
	  ServerAlias www.${http_host}
	  ServerAlias *.${http_host}
	  DocumentRoot ${http_docroot}
	  RailsEnv development
	  SetEnv PATH /usr/bin:/usr/sbin:/opt/local/bin:/opt/local/sbin
	  PassengerDefaultUser www
	  PassengerDefaultGroup www
	  <Directory ${http_docroot}>
	    Allow from all
	    Options -MultiViews
	    Require all granted
	  </Directory>
	</VirtualHost>
	EOF
}
nginx_create_config() {
	# Create first part of configuration
	cat > ${nginx_confdir_vhosts}/${http_conffile} <<-EOF
	server {
	  listen 80;
	  server_name ${http_host} www.${http_host} *.${http_host};

	EOF

	if [[ ${opt_t} ]]; then
		# Create tomcat part of configuration
		cat >> ${nginx_confdir_vhosts}/${http_conffile} <<-EOF
		  location ~ ^/(assets) {
		    root ${http_docroot};
		  }

		  location / {
		    proxy_set_header X-Forwarded-Host \$host;
		    proxy_set_header X-Forwarded-Server \$host;
		    proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
		    proxy_pass http://127.0.0.1:8080/;
		  }
		}
		EOF
	else
		# Create php part of configuration
		if [[ ${opt_p} ]]; then
			cat >> ${nginx_confdir_vhosts}/${http_conffile} <<-EOF
			  root ${http_docroot};

			  location / {
			    index index.php index.html index.htm;
			    try_files \$uri \$uri/ /index.php?q=\$request_uri;
			  }
			  location ~ \.php$ {
			    include /opt/local/etc/nginx/fastcgi.conf;
			    fastcgi_pass 127.0.0.1:9000;
			  }
			}
			EOF
		else
			cat >> ${nginx_confdir_vhosts}/${http_conffile} <<-EOF
			  root ${http_docroot};

			  location / {
			    index index.html index.htm;
			  }
			}
			EOF
		fi
	fi
}
nginx_create_sslconfig() {
	# Create first part of configuration
	cat > ${nginx_confdir_vhosts}/${http_sslconffile} <<-EOF
	server {
	  listen 443;
	  server_name ${http_host} www.${http_host} *.${http_host};
	  ssl on;
	  #ssl_session_timeout  5m;
	  #ssl_protocols  SSLv2 SSLv3 TLSv1;
	  #ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
	  #ssl_prefer_server_ciphers   on;
	  ssl_certificate ${nginx_confdir}/ssl/${http_host}.crt;
	  ssl_certificate_key ${nginx_confdir}/ssl/${http_host}.key;

	  root ${http_docroot};

	EOF

	# Create php part of configuration
	if [[ ${opt_p} ]]; then
		cat >> ${nginx_confdir_vhosts}/${http_sslconffile} <<-EOF
		  location / {
		    index index.php index.html index.htm;
		    try_files \$uri \$uri/ /index.php?q=\$request_uri;
		  }
		  location ~ \.php$ {
		    include /opt/local/etc/nginx/fastcgi.conf;
		    fastcgi_pass 127.0.0.1:9000;
		  }
		}
		EOF
	else
		cat >> ${nginx_confdir_vhosts}/${http_sslconffile} <<-EOF
		  location / {
		    index index.html index.htm;
		  }
		}
		EOF
	fi
}
case ${http_type} in
	apache|Apache)
		# Check if apache is installed through pkgsrc
		[[ $(svcs -H -o FMRI pkgsrc/apache > /dev/null 2>&1)$? -ne "0" ]] && fail "Apache is not installed.  You'll need to install with:\n! # pkgin install apache";

		# Check if httpd.conf exists
		[[ ! -s ${apache_confdir}/httpd.conf ]] && fail "The Apache configuration file ${apache_confdir}/httpd.conf doesn't exist.";

		# If virtualhosts directory doesn't exist create it
		if [[ ! -d ${apache_confdir_vhosts} ]]; then
			mkdir -p ${apache_confdir_vhosts};
			echo "* Created ${apache_confdir_vhosts} directory.";
		fi

		# If docroot doesn't exist then create it	
		[[ ! -d ${http_docroot} ]] && mkdir -p ${http_docroot};

		# If configuration doesn't exist then create it
		if [[ ${opt_s} ]]; then
			[[ -s ${apache_confdir_vhosts}/${http_sslconffile} ]] && fail "The configuration file ${apache_confdir_vhosts}/${http_sslconffile} already exists.";
			apache_create_sslconfig;

			cat <<-EOF 
			* Created Apache (SSL) configuration ${apache_confdir_vhosts}/${http_sslconffile}.
			  Settings:
			    Hosts:    ${http_host} *.${http_host} www.${http_host}
			    Port:     443 
			    Docroot:  ${http_docroot}
			    SSL cert: ${apache_confdir_vhosts}/${http_host}.crt
			    SSL key:  ${apache_confdir_vhosts}/${http_host}.key

			EOF
		elif [[ ${opt_t} ]]; then
			[[ -s ${apache_confdir_vhosts}/${http_conffile} ]] && fail "The configuration file ${apache_confdir_vhosts}/${http_conffile} already exists.";
			[[ ! -d ${http_docroot}/assets ]] && mkdir -p ${http_docroot}/assets;
			apache_create_config;

			cat <<-EOF 
			* Created Apache (Tomcat) configuration ${apache_confdir_vhosts}/${http_conffile}.
			  Settings:
			    Hosts:         ${http_host} *.${http_host} www.${http_host}
			    Port:          80
			    Docroot:       ${http_docroot}
			    Static Assets: ${http_docroot}/assets
			    Proxy:         Pass/Reverse to http://localhost:8080

			EOF
		elif [[ ${opt_r} ]]; then
			[[ -s ${apache_confdir_vhosts}/${http_conffile} ]] && fail "The configuration file ${apache_confdir_vhosts}/${http_conffile} already exists.";
			apache_create_railsconfig;

			cat <<-EOF 
			* Created Apache (Rails) configuration ${apache_confdir_vhosts}/${http_conffile}.
			  Settings:
			    Hosts:    ${http_host} *.${http_host} www.${http_host}
			    Port:     80
			    Docroot:  ${http_docroot}
			    RailsEnv: development	

			EOF

		else
			[[ -s ${apache_confdir_vhosts}/${http_conffile} ]] && fail "The configuration file ${apache_confdir_vhosts}/${http_conffile} already exists.";
			apache_create_config;

			cat <<-EOF 
			* Created Apache configuration ${apache_confdir_vhosts}/${http_conffile}.
			  Settings:
			    Hosts:   ${http_host} *.${http_host} www.${http_host}
			    Port:    80
			    Docroot: ${http_docroot}

			EOF
		fi

		if [[ ${opt_s} ]] && [[ $(grep -q "^Listen 0.0.0.0:443$" ${apache_confdir}/httpd.conf)$? -eq 1 ]]; then
			echo -ne "  For changes to take you will need:\n\n  Include etc/httpd/virtualhosts/*.conf\n  Listen 0.0.0.0:443\n\n  in your ${apache_confdir}/httpd.conf and restart apache with:\n  # svcadm restart pkgsrc/apache\n\n";
		else
			echo -ne "  For changes to take you will need:\n\n  Include etc/httpd/virtualhosts/*.conf\n\n  in your ${apache_confdir}/httpd.conf and restart apache with:\n  # svcadm restart pkgsrc/apache\n\n";
		fi

		if [[ ${opt_p} ]] && [[ $(pkgin list | awk '{ print $1 }' | grep -q "php[0-9][0-9]-fpm")$? -eq 1 ]]; then
			echo -ne "  For PHP support with apache you will need to:\n  # pkgin install phpXX-fpm\n  # svcadm enable pkgsrc/php-fpm\n\n  replacing 'XX' with your appropriate version.\n\n";
		fi

		if [[ ${opt_r} ]] && [[ $(pkgin list | awk '{ print $1 }' | egrep -q "ap[0-9][0-9]?-ruby[0-9][0-9][0-9]?-passenger")$? -eq 1 ]]; then
			echo -ne "  For Rails support (mod_passenger) with apache you will need to:\n  # pkgin install apXX-ruby-XXX-passenger\n\n  and you will need:\n\n";
			cat <<-EOF 
			  LoadModule passenger_module lib/httpd/mod_passenger.so
			  <IfModule mod_passenger.c>
			    PassengerRoot /opt/local/lib/ruby/vendor_ruby/phusion_passenger/locations.ini
			    PassengerRuby /opt/local/bin/rubyXXX
			  </IfModule>

			EOF
			echo -ne "  in your ${apache_confdir}/httpd.conf replacing 'XX' with your appropriate\n  versions.\n\n";
		elif [[ ${opt_r} ]]; then
			echo -ne "  For Rails support (mod_passenger) with apache you will need:\n\n";
			cat <<-EOF 
			  LoadModule passenger_module lib/httpd/mod_passenger.so
			  <IfModule mod_passenger.c>
			    PassengerRoot /opt/local/lib/ruby/vendor_ruby/phusion_passenger/locations.ini
			    PassengerRuby /opt/local/bin/rubyXXX
			  </IfModule>

			EOF
			echo -ne "  in your ${apache_confdir}/httpd.conf replacing 'XX' with your appropriate\n  versions.\n\n";
		fi
		;;

	nginx|Nginx)
		# Check if nginx is installed through pkgsrc
		[[ $(svcs -H -o FMRI pkgsrc/nginx > /dev/null 2>&1)$? -ne "0" ]] && fail "Nginx is not installed.  You'll need to install with:\n! # pkgin install nginx";

		# Check if nginx.conf exists
		[[ ! -s ${nginx_confdir}/nginx.conf ]] && fail "The configuration file ${nginx_confdir}/nginx.conf doesn't exist.";

		# If virtualhosts directory doesn't exist create it
		if [[ ! -d ${nginx_confdir_vhosts} ]]; then
			mkdir -p ${nginx_confdir_vhosts};
			echo "* Created ${nginx_confdir_vhosts} directory.";
		fi

		# If docroot doesn't exist then create it	
		[[ ! -d ${http_docroot} ]] && mkdir -p ${http_docroot};

		# If configuration doesn't exist then create it
		if [[ ${opt_s} ]]; then
			[[ -s ${nginx_confdir_vhosts}/${http_sslconffile} ]] && fail "The configuration file ${nginx_confdir_vhosts}/${http_sslconffile} already exists.";
			[[ ! -d ${nginx_confdir}/ssl ]] && mkdir -p ${nginx_confdir}/ssl;
			nginx_create_sslconfig;

			cat <<-EOF 
			* Created Nginx (SSL) configuration ${nginx_confdir_vhosts}/${http_sslconffile}.
			  Settings:
			    Hosts:    ${http_host} *.${http_host} www.${http_host}
			    Port:     443 
			    Docroot:  ${http_docroot}
			    SSL cert: ${nginx_confdir}/ssl/${http_host}.crt
			    SSL key:  ${nginx_confdir}/ssl/${http_host}.key

			EOF

			echo -ne "  Your certificate and key files must exist or nginx will fail to start.\n";

		elif [[ ${opt_t} ]]; then
			[[ -s ${nginx_confdir_vhosts}/${http_conffile} ]] && fail "The configuration file ${nginx_confdir_vhosts}/${http_conffile} already exists.";
			[[ ! -d ${http_docroot}/assets ]] && mkdir -p ${http_docroot}/assets;
			nginx_create_config;

			cat <<-EOF 
			* Created Nginx (Tomcat) configuration ${nginx_confdir_vhosts}/${http_conffile}.
			  Settings:
			    Hosts:         ${http_host} *.${http_host} www.${http_host}
			    Port:          80
			    Docroot:       ${http_docroot}
			    Static Assets: ${http_docroot}/assets
			    Proxy:         Pass/Reverse to http://localhost:8080

			EOF
		else
			[[ -s ${nginx_confdir_vhosts}/${http_conffile} ]] && fail "The configuration file ${nginx_confdir_vhosts}/${http_conffile} already exists.";
			nginx_create_config;

			cat <<-EOF
			* Created Nginx configuration ${nginx_confdir_vhosts}/${http_conffile}.
			  Settings:
			    Hosts:   ${http_host} *.${http_host} www.${http_host}
			    Port:    80
			    Docroot: ${http_docroot}

			EOF
		fi

		echo -ne "  For changes to take you will need:\n\n  include /opt/local/etc/nginx/virtualhosts/*;\n\n  in your ${nginx_confdir}/nginx.conf http{} block and restart nginx with:\n  # svcadm restart pkgsrc/nginx\n\n";

		if [[ ${opt_p} ]] && [[ $(pkgin list | awk '{ print $1 }' | grep -q "php[0-9][0-9]-fpm")$? -eq 1 ]]; then
			echo -ne "  For PHP support with nginx you will need to:\n  # pkgin install phpXX-fpm\n  # svcadm enable pkgsrc/php-fpm\n\n  replacing 'XX' with your appropriate version.\n\n";
		fi

		;;

	*)
		usage;
esac
