#!/bin/bash
#
# Apache 2 Tools.
#
# For suggestion, bug reports, please contact Pierre-Yves Landuré <pierre-yves@landure.fr>


SCRIPT_NAME="$(command basename ${0})"

# Print this script help.
function usage {
  command echo "
This tool ease Apache 2 HTTP server administration from command line.

Usage :

  ${SCRIPT_NAME} setup-apache2-php5
  ${SCRIPT_NAME} setup-apache2
  ${SCRIPT_NAME} add-virtual-host hostname path [ allow_override ]
  ${SCRIPT_NAME} add-ssl-virtual-host hostname path key-file cert-file [ bind_ip [ allow_override ] ]
  ${SCRIPT_NAME} add-reverse-proxy hostname proxied_url
  ${SCRIPT_NAME} add-ssl-reverse-proxy hostname proxied_url key-file cert-file [ bind_ip ]
  ${SCRIPT_NAME} add-redirect hostname target_url
  ${SCRIPT_NAME} add-ssl-redirect hostname target_url key-file cert-file [ bind_ip ]
  ${SCRIPT_NAME} add-custom hostname custom_apache_config
  ${SCRIPT_NAME} add-ssl-custom hostname custom_apache_config key-file cert-file [ bind_ip ]

  * setup-apache2-php5, setup-a2-php5 : Install Apache 2 with PHP 5 support.
  * setup-apache2 : Install Apache 2 and setup a default configuration.
  * setup-fail2ban : Install fail2ban for Apache 2 attack prevention.
  * disable-cgi-bin : Disable CGI-BIN folders in default Apache 2 configuration.
  * add-virtual-host, add-vhost : Add a virtual host serving the path content
      on the hostname. Optionnaly, you can set a default AllowOverride directive.
  * add-ssl-virtual-host, add-ssl-vhost : Add a SSL virtual host serving the path content
      on the hostname. Optionnaly, you can set a default AllowOverride directive.
  * add-reverse-proxy : Add a virtual host serving a reverse proxied URL.
  * add-ssl-reverse-proxy : Add a SSL virtual host serving a reverse proxied URL.
  * add-redirect : Add a virtual host redirecting a domain to the given target URL.
  * add-ssl-redirect : Add a SSL virtual host redirecting a domain to the given target URL.
"
  exit 1
} # usage



# Common Apache 2 Vhost template
VHOST_TEMPLATE[0]="<VirtualHost *:80>
  # Uncomment this line and set it up with your actual webmaster email
  # or with your real email.
  #ServerAdmin webmaster@my-domain.com

  # Your actual domain name, on witch this virtual host is available.
  ServerName SITE_HOSTNAME

  # You may want your site to be available on other domain names, this is
  # what alias are for.
  # You can use the * wildcard caracter to match multiple sub-domains.
  #ServerAlias www2.my-domain.com www.my-other-domain.com *.yet-another-domain.com

  # Theses lines only apply of the rewrite module is enabled.
  # This is a security enhancement recommanded by the nessus tool.
  <IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
    RewriteRule .* - [F]
  </IfModule>

  # These section tel Apache 2 that it can follow symbolic links (cf. ln -s)
  # on your system. This can avoid a lot of problems... as well at
  # it can be a security issue if the links points to /etc...
  # be carefull at what you link :)
  <Directory />
    Options FollowSymLinks
    AllowOverride None
  </Directory>
"

VHOST_TEMPLATE[1]="
  # This Location directives allow users to access to the proxyfied contents.
  # Do not remove this if you want your site to work :).
  <Location />
    Order deny,allow
    Allow from all
  </Location>

</VirtualHost>"



LOGS_TEMPLATE="
  # The error log and access log. This can be used by awstats
  # Note : since we keed theses logs in /var/log/apache2, they are
  # automaticaly rotated by logrotate :D.
  ErrorLog /var/log/apache2/SITE_HOSTNAME-error.log
  LogLevel warn
  CustomLog /var/log/apache2/SITE_HOSTNAME-access.log combined
"



SSL_TEMPLATE="
  <IfModule mod_ssl.c>
    #
    # SSL magic
    #

    # We enable the SSL engine. Without this line, we use HTTP, not HTTPS.
    SSLEngine On

    # We allow only \"high\" and \"medium\" security key lengths.
    SSLCipherSuite HIGH:MEDIUM

    # We allow SSLv3 and TLSv1 only, we reject the old SSLv2.
    SSLProtocol all -SSLv2

    # Server public certificate file:
    SSLCertificateFile CERTIFICATE_FILE

    # Server private key file:
    SSLCertificateKeyFile KEY_FILE

    # SSLCACertificatePath /etc/ssl/certs
    # SSLCertificateChainFile CHAIN_FILE

    #   SSL Protocol Adjustments:
    #   The safe and default but still SSL/TLS standard compliant shutdown
    #   approach is that mod_ssl sends the close notify alert but doesn't wait for
    #   the close notify alert from client. When you need a different shutdown
    #   approach you can use one of the following variables:
    #   o ssl-unclean-shutdown:
    #     This forces an unclean shutdown when the connection is closed, i.e. no
    #     SSL close notify alert is send or allowed to received.  This violates
    #     the SSL/TLS standard but is needed for some brain-dead browsers. Use
    #     this when you receive I/O errors because of the standard approach where
    #     mod_ssl sends the close notify alert.
    #   o ssl-accurate-shutdown:
    #     This forces an accurate shutdown when the connection is closed, i.e. a
    #     SSL close notify alert is send and mod_ssl waits for the close notify
    #     alert of the client. This is 100% SSL/TLS standard compliant, but in
    #     practice often causes hanging connections with brain-dead browsers. Use
    #     this only for browsers where you know that their SSL implementation
    #     works correctly.
    #   Notice: Most problems of broken clients are also related to the HTTP
    #   keep-alive facility, so you usually additionally want to disable
    #   keep-alive for those clients, too. Use variable \"nokeepalive\" for this.
    #   Similarly, one has to force some clients to use HTTP/1.0 to workaround
    #   their broken HTTP/1.1 implementation. Use variables \"downgrade-1.0\" and
    #   \"force-response-1.0\" for this.
    BrowserMatch \"MSIE [2-6]\" \
      nokeepalive ssl-unclean-shutdown \
      downgrade-1.0 force-response-1.0
    # MSIE 7 and newer should be able to use keepalive
    BrowserMatch \"MSIE [17-9]\" ssl-unclean-shutdown
  </IfModule>
"



# Apache 2 standard Virtual Host template.
PATH_TEMPLATE="
  # The root folder of this virtual host.
  DocumentRoot SITE_PATH

  # Some options for the root folder.
  # Read Apache 2 documentation to know exactly what is done.
  <Directory SITE_PATH>
    Options Indexes FollowSymLinks MultiViews

    # If you want to enable overrides, you should read:
    # http://httpd.apache.org/docs/2.0/mod/core.html#allowoverride
    AllowOverride ALLOW_OVERRIDE

    Order allow,deny
    allow from all
  </Directory>
"



REVERSE_PROXY_TEMPLATE="
  <IfModule mod_rewrite.c>
    <IfModule mod_proxy.c>
      # Do not ever never comment this line !
      # This line prevent your web server to be used
      # as a proxy server by lurkers and other lamers.
      ProxyRequests   Off

      # This little option pass the hostname to the proxyfied server.
      # This allow you to setup virtual hosts on the proxyfied server.
      # Yay ! This can be a life saver, so trust me, you want this option On.
      ProxyPreserveHost On

      # Fix IE problem (http error 408/409)
      SetEnv proxy-nokeepalive 1

      <IfModule mod_ssl.c>
        # Turn this on if the site behind the reverse proxy is on HTTPS.
        SSLProxyEngine Off
      </IfModule>

      # Declare the current request protocol.
      RequestHeader set X-Forwarded-Proto \"http\"

      # Here is the magic that proxyfy the LAN server. 
      # The first line is .... i don't remember what...
      # but trust me, it is usefull ;p.
      # The second line is a rewrite rule that do the proxy
      # magic. I was used to use a ProxyPass rule to do this work, but it
      # turned out that sometimes ProxyPass give you a 503 error when under
      # heavy load. The RewriteRule does not have this flow.
      ProxyPassReverse  /       SITE_BEHIND
      RewriteRule       ^/(.*)  SITE_BEHIND\$1  [P,L]

    </IfModule>
  </IfModule>
"



REDIRECT_TEMPLATE="
  # Redirect every body to the HTTPS site.
  # This make sure that all users use secure version of the site.
  # Note the \"permanent\" : It is good for search engine optimization :D.
  Redirect permanent / REDIRECT_TARGET
"



# Get the absolute path for a file or directory.
#
# @param string $path A relative path.
#
# @return ${REALPATH} A absolute path.
REALPATH=""
function realpath {
  command test ${#} -ne 1 && exit 1
  REALPATH=$(/bin/readlink -f "${1}")
} # realpath



# Check if a binary is present
#
# @param string $binary The binary to check.
# @param string $package The package the binary come from.
#
# @return Exit with error if the binary is missing.
function check_binary {
  command test ${#} -ne 2 && exit 1

  # Test the binary presence.
  if [ -z "$(which "${1}")" ]; then
    echo "Error : '${1}' is missing. Please install package '${2}'."
    exit 1
  fi
} # check_binary



# Check if MySQL connection is working
#
# @param string $mysql_host The MySQL host.
# @param string $mysql_user The MySQL user.
# @param string $mysql_password The MySQL password.
# @param string $mysql_db The MySQL DB.
#
# @return Exit with error if connection to MySQL fail.
function check_mysql {
  command test ${#} -ne 4 && exit 1

  # Test the MySQL connection.
  if ! command mysql --execute="SELECT 1" \
            --host="${1}" --user="${2}" --password="${3}" \
            "${4}" 2>&1 > /dev/null; then
    echo "Error : Unable to connect to MySQL. Please provide valid MySQL connection parameters."
    exit 1
  fi
} # check_mysql



# Download a file from the given URL.
#
# @param string $url The URL of the file to download.
#
# @return ${DOWNLOAD_FILE} The path to the downloaded file.
DOWNLOAD_FILE=""
function download_file {
  command test ${#} -ne 1 && exit 1

  # Download a file.
  DOWNLOAD_FILE="$(command mktemp)"
  command wget --quiet "${1}" \
      --output-document="${DOWNLOAD_FILE}"

  if [ ! -s "${DOWNLOAD_FILE}" ]; then
    command rm "${DOWNLOAD_FILE}"
    echo "Error : Unable to download file from '${1}'."
    exit 1
  fi
} # download_file



# Download and uncompress a tgz file from the given URL.
#
# @param string $url The URL of the file to download.
#
# @return ${DOWNLOAD_TGZ} The path to the extracted content.
DOWNLOAD_TGZ=""
function download_tgz {
  command test ${#} -ne 1 && exit 1

  download_file "${1}"

  # Untar the downloaded file and place it at its final location.
  DOWNLOAD_TGZ="$(command mktemp -d)"
  command tar --directory "${DOWNLOAD_TGZ}" -xzf "${DOWNLOAD_FILE}"
  command rm "${DOWNLOAD_FILE}"

  if [ $(command ls -1 --all "${DOWNLOAD_TGZ}" | command wc --lines) -eq 0 ]; then
    echo "Error : unable to untar file downloaded from '${1}'."
    exit 1
  fi
} # download_tgz



# Read the eth0 IP.
#
# @return A IP address.
function eth0_ip {
  command ifconfig eth0 \
            | command grep "inet adr" \
            | command sed -e 's/.*inet adr:\([^ ]*\).*/\1/'
} # eth0_ip



# Reload Apache 2 configuration only if valid.
#
# @return void
function apache2_reload {
  if command apache2ctl -t; then
    /etc/init.d/apache2 reload
  else
    echo "Error in Apache 2 configuration : reload cancelled."
    exit 1
  fi
  exit 0
} # apache2_reload



# Force Apache 2 configuration reload only if valid.
#
# @return void
function apache2_force_reload {
  if command apache2ctl -t; then
    /etc/init.d/apache2 force-reload
  else
    echo "Error in Apache 2 configuration : forced reload cancelled."
    exit 1
  fi

  exit 0
} # apache2_force_reload



# Check for binaries presence
check_binary "basename" "coreutils"
check_binary "dirname" "coreutils"
check_binary "tar" "tar"
check_binary "mktemp" "mktemp"
check_binary "sed" "sed"
#check_binary "wget" "wget"
#check_binary "unzip" "unzip"
#check_binary "apg" "apg"
#check_binary "mysql" "mysql-client"

# Check if at least one args given.
command test ${#} -eq 0 && usage

case "${1}" in

  setup-apache2-php5|setup-a2-php5 )
    # Installating apache2 with php5.
    command apt-get -y install libapache2-mod-php5
    command a2enmod php5

    ${0} setup-apache2

    exit 0
    ;;

  setup-apache2 )
    command apt-get -y install apache2
    command a2enmod rewrite

    check_binary "a2ensite" "apache2"

    # Setting up apache to listen on port 80.
    if [ -z "$(command grep 'NameVirtualHost.*:80' /etc/apache2/ports.conf)" ]; then
      command sed -i -e '/Listen[\t ]*80/i\
NameVirtualHost *:80' /etc/apache2/ports.conf
    fi

    if [ -z "$(command grep 'VirtualHost[ \t]*\*:80' /etc/apache2/sites-available/default)" ]; then
      command sed -i -e 's/\(VirtualHost[ \t]*\*\)>/\1:80>/g' \
                -e 's/^\(NameVirtualHost.*\)$/#\1/g' \
             /etc/apache2/sites-available/default
    fi

    apache2_force_reload
    exit 0
    ;;



  setup-fail2ban )
    # Installing fail2ban for Apache 2 attack prevention.
    command apt-get -y install fail2ban

    command sed -i -e '/\[apache\]/, /filter/ {0,/^enabled.*/ s//enabled = true/ }' \
                  -e '/\[apache-noscript\]/, /filter/ {0,/^enabled.*/ s//enabled = true/ }' \
                  -e '/\[apache-overflows\]/, /filter/ {0,/^enabled.*/ s//enabled = true/ }' \
                "/etc/fail2ban/jail.conf"

    /etc/init.d/fail2ban restart

    exit 0
    ;;



  disable-cgi-bin )
    check_binary "apache2ctl" "apache2"
    command sed -i -e 's|^.*ScriptAlias.*/cgi-bin/.*$|#\0|' \
                  -e '/Directory.*cgi-bin/,/\/Directory/s/^.*/#\0/' \
         "/etc/apache2/sites-available/default"{,-ssl}

    apache2_force_reload
    exit 0
    ;;



  add-virtual-host|add-vhost )
    # Check if valid number of arguments given (6).
    command test ${#} -ne 3 -a ${#} -ne 4 && usage

    check_binary "apache2ctl" "apache2"

    command a2enmod rewrite > /dev/null

    SITE_HOSTNAME="${2}"
    realpath "${3}"
    SITE_PATH="${REALPATH}"
    ALLOW_OVERRIDE="${4}"

    if [ -z "${ALLOW_OVERRIDE}" ]; then
      ALLOW_OVERRIDE="None"
    fi

    command echo "${VHOST_TEMPLATE[0]}
${LOGS_TEMPLATE}
${PATH_TEMPLATE}
${VHOST_TEMPLATE[1]}" \
      | command sed -e "s|SITE_HOSTNAME|${SITE_HOSTNAME}|g" \
                    -e "s|SITE_PATH|${SITE_PATH}|g" \
                    -e "s|ALLOW_OVERRIDE|${ALLOW_OVERRIDE}|g" \
         > "/etc/apache2/sites-available/http-${SITE_HOSTNAME}"

    command a2ensite "http-${SITE_HOSTNAME}"

    apache2_reload
    exit 0
    ;;



  add-reverse-proxy|add-reverse )
    # Check if valid number of arguments given (6).
    command test ${#} -ne 3 && usage

    check_binary "apache2ctl" "apache2"

    command a2enmod rewrite > /dev/null
    command a2enmod proxy_http > /dev/null
    command a2enmod headers > /dev/null

    SITE_HOSTNAME="${2}"
    SITE_BEHIND="${3}"

    SITE_BEHIND=$(command echo "${SITE_BEHIND}/" \
             | command sed -e 's|//$|/|')
    SITE_BEHIND_URI=$(command echo "${SITE_BEHIND}" \
             | command sed -e 's|[^:]*://[^/]*\(/.*\)/$|\1|')

    SSL_PROXY_ENGINE="Off"
    if [ -n "$(echo ${SITE_BEHIND_URI} | command grep "^https")" ]; then
      SSL_PROXY_ENGINE="On"
    fi

    command echo "${VHOST_TEMPLATE[0]}
${LOGS_TEMPLATE}
${REVERSE_PROXY_TEMPLATE}
${VHOST_TEMPLATE[1]}" \
      | command sed -e "s|SITE_HOSTNAME|${SITE_HOSTNAME}|g" \
                    -e "s|SITE_BEHIND|${SITE_BEHIND}|g" \
                    -e "s|SSLProxyEngine.*|SSLProxyEngine ${SSL_PROXY_ENGINE}|" \
         > "/etc/apache2/sites-available/http-${SITE_HOSTNAME}"

    command a2ensite "http-${SITE_HOSTNAME}"

    apache2_reload
    exit 0
    ;;



  add-ssl-virtual-host|add-ssl-vhost )
    # Check if valid number of arguments given (6).
    command test ${#} -lt 5 && usage

    check_binary "apache2ctl" "apache2"

    command a2enmod ssl > /dev/null
    command a2enmod rewrite > /dev/null

    SITE_HOSTNAME="${2}"
    realpath "${3}"
    SITE_PATH="${REALPATH}"
    realpath "${4}"
    KEY_FILE="${REALPATH}"
    realpath "${5}"
    CERTIFICATE_FILE="${REALPATH}"
    BIND_IP="${6}"
    ALLOW_OVERRIDE="${7}"

    if [ -z "${BIND_IP}" ]; then
      BIND_IP=$(eth0_ip)
    fi

    if [ -z "${ALLOW_OVERRIDE}" ]; then
      ALLOW_OVERRIDE="None"
    fi

    command echo "${VHOST_TEMPLATE[0]}
${LOGS_TEMPLATE}
${SSL_TEMPLATE}
${PATH_TEMPLATE}
${VHOST_TEMPLATE[1]}" \
      | command sed -e "s|SITE_HOSTNAME|${SITE_HOSTNAME}|g" \
                    -e "s|SITE_PATH|${SITE_PATH}|g" \
                    -e "s|*:80|${BIND_IP}:443|g" \
                    -e "s|CERTIFICATE_FILE|${CERTIFICATE_FILE}|g" \
                    -e "s|KEY_FILE|${KEY_FILE}|g" \
                    -e "s|ALLOW_OVERRIDE|${ALLOW_OVERRIDE}|g" \
         > "/etc/apache2/sites-available/https-${SITE_HOSTNAME}"

    command a2ensite "https-${SITE_HOSTNAME}"

    apache2_reload
    exit 0
    ;;



  add-ssl-reverse-proxy )
    # Check if valid number of arguments given (6).
    command test ${#} -lt 5 && usage

    check_binary "apache2ctl" "apache2"

    command a2enmod ssl > /dev/null
    command a2enmod rewrite > /dev/null
    command a2enmod proxy_http > /dev/null
    command a2enmod headers > /dev/null

    SITE_HOSTNAME="${2}"
    SITE_BEHIND="${3}"
    realpath "${4}"
    KEY_FILE="${REALPATH}"
    realpath "${5}"
    CERTIFICATE_FILE="${REALPATH}"
    BIND_IP="${6}"
    ALLOW_OVERRIDE="${7}"

    if [ -z "${BIND_IP}" ]; then
      BIND_IP=$(eth0_ip)
    fi

    SITE_BEHIND=$(command echo "${SITE_BEHIND}/" \
             | command sed -e 's|//$|/|')
    SITE_BEHIND_URI=$(command echo "${SITE_BEHIND}" \
             | command sed -e 's|[^:]*://[^/]*\(/.*\)/$|\1|')

    SSL_PROXY_ENGINE="Off"
    if [ -n "$(echo ${SITE_BEHIND_URI} | command grep "^https")" ]; then
      SSL_PROXY_ENGINE="On"
    fi

    command echo "${VHOST_TEMPLATE[0]}
${LOGS_TEMPLATE}
${SSL_TEMPLATE}
${REVERSE_PROXY_TEMPLATE}
${VHOST_TEMPLATE[1]}" \
      | command sed -e "s|SITE_HOSTNAME|${SITE_HOSTNAME}|g" \
                    -e "s|SITE_BEHIND|${SITE_BEHIND}|g" \
                    -e "s|SSLProxyEngine.*|SSLProxyEngine ${SSL_PROXY_ENGINE}|" \
                    -e "s|*:80|${BIND_IP}:443|g" \
                    -e "s|CERTIFICATE_FILE|${CERTIFICATE_FILE}|g" \
                    -e "s|KEY_FILE|${KEY_FILE}|g" \
                    -e "s|X-Forwarded-Proto \"http|&s|" \
         > "/etc/apache2/sites-available/https-${SITE_HOSTNAME}"

    command a2ensite "https-${SITE_HOSTNAME}"

    apache2_reload
    exit 0
    ;;



  add-redirect)
    # Check if valid number of arguments given.
    command test ${#} -ne 3 && usage

    check_binary "apache2ctl" "apache2"

    command a2enmod rewrite > /dev/null

    SITE_HOSTNAME="${2}"
    REDIRECT_TARGET=$(command echo "${3}/" \
             | command sed -e 's|//$|/|')


    REDIRECT_TARGET_URI=$(command echo "${REDIRECT_TARGET}" \
             | command sed -e 's|[^:]*://[^/]*\(/.*\)/$|\1|')

    command echo "${VHOST_TEMPLATE[0]}
${REDIRECT_TEMPLATE}
${VHOST_TEMPLATE[1]}" \
      | command sed -e "s|SITE_HOSTNAME|${SITE_HOSTNAME}|g" \
                    -e "s|REDIRECT_TARGET|${REDIRECT_TARGET}|g" \
         > "/etc/apache2/sites-available/redirect-http-${SITE_HOSTNAME}"

    command a2ensite "redirect-http-${SITE_HOSTNAME}"

    apache2_reload
    exit 0
    ;;



  add-ssl-redirect )
    # Check if valid number of arguments given (6).
    command test ${#} -lt 5 && usage

    check_binary "apache2ctl" "apache2"

    command a2enmod ssl > /dev/null
    command a2enmod rewrite > /dev/null

    SITE_HOSTNAME="${2}"
    REDIRECT_TARGET=$(command echo "${3}/" \
             | command sed -e 's|//$|/|')
    realpath "${4}"
    KEY_FILE="${REALPATH}"
    realpath "${5}"
    CERTIFICATE_FILE="${REALPATH}"
    BIND_IP="${6}"

    if [ -z "${BIND_IP}" ]; then
      BIND_IP=$(eth0_ip)
    fi

    REDIRECT_TARGET_URI=$(command echo "${REDIRECT_TARGET}" \
             | command sed -e 's|[^:]*://[^/]*\(/.*\)/$|\1|')

    command echo "${VHOST_TEMPLATE[0]}
${SSL_TEMPLATE}
${REDIRECT_TEMPLATE}
${VHOST_TEMPLATE[1]}" \
      | command sed -e "s|SITE_HOSTNAME|${SITE_HOSTNAME}|g" \
                    -e "s|REDIRECT_TARGET|${REDIRECT_TARGET}|g" \
                    -e "s|*:80|${BIND_IP}:443|g" \
                    -e "s|CERTIFICATE_FILE|${CERTIFICATE_FILE}|g" \
                    -e "s|KEY_FILE|${KEY_FILE}|g" \
         > "/etc/apache2/sites-available/redirect-https-${SITE_HOSTNAME}"

    command a2ensite "redirect-https-${SITE_HOSTNAME}"

    apache2_reload
    exit 0
    ;;



  add-custom )
    # Check if valid number of arguments given (6).
    command test ${#} -ne 3 && usage

    check_binary "apache2ctl" "apache2"

    command a2enmod rewrite > /dev/null

    SITE_HOSTNAME="${2}"
    CUSTOM_TEMPLATE="${3}"

    command echo "${VHOST_TEMPLATE[0]}
${LOGS_TEMPLATE}
${CUSTOM_TEMPLATE}
${VHOST_TEMPLATE[1]}" \
      | command sed -e "s|SITE_HOSTNAME|${SITE_HOSTNAME}|g" \
         > "/etc/apache2/sites-available/http-${SITE_HOSTNAME}"

    command a2ensite "http-${SITE_HOSTNAME}"

    apache2_reload
    exit 0
    ;;



  add-ssl-custom )
    # Check if valid number of arguments given (6).
    command test ${#} -lt 5 && usage

    check_binary "apache2ctl" "apache2"

    command a2enmod ssl > /dev/null
    command a2enmod rewrite > /dev/null

    SITE_HOSTNAME="${2}"
    CUSTOM_TEMPLATE="${3}"

    realpath "${4}"
    KEY_FILE="${REALPATH}"
    realpath "${5}"
    CERTIFICATE_FILE="${REALPATH}"
    BIND_IP="${6}"

    if [ -z "${BIND_IP}" ]; then
      BIND_IP=$(eth0_ip)
    fi

    command echo "${VHOST_TEMPLATE[0]}
${LOGS_TEMPLATE}
${SSL_TEMPLATE}
${CUSTOM_TEMPLATE}
${VHOST_TEMPLATE[1]}" \
      | command sed -e "s|SITE_HOSTNAME|${SITE_HOSTNAME}|g" \
                    -e "s|*:80|${BIND_IP}:443|g" \
                    -e "s|CERTIFICATE_FILE|${CERTIFICATE_FILE}|g" \
                    -e "s|KEY_FILE|${KEY_FILE}|g" \
         > "/etc/apache2/sites-available/https-${SITE_HOSTNAME}"

    command a2ensite "https-${SITE_HOSTNAME}"

    apache2_reload
    exit 0
    ;;



  * )
    echo "Error : '${1}' is not a valid action."
    usage
    ;;
esac

exit 0
