#!/bin/bash -e
# Startup script to run the ASR Engine as a web service over HTTPS (i.e. with SSL encryption).

APACHE_SSL_CONFIG=/etc/apache2/ssl.conf

echo "==== Checking for SSL certificate..."
apache_fullchain_path=$(grep '^ *SSLCertificateFile' $APACHE_SSL_CONFIG | awk '{print $2}')
if [ -e "$apache_fullchain_path" ]; then
    echo "INFO: Found SSL certificate configured for Apache (at $apache_fullchain_path)."
else
    echo "INFO: Did not find SSL certificate configured for Apache (as in $APACHE_SSL_CONFIG)."
    echo

    # Install a certificate with Certbot, unless there's already one installed.
    sudo certbot certificates &> /tmp/certbot-certificates.txt
    num_certificates=$(grep 'Certificate Name:' /tmp/certbot-certificates.txt | wc -l)
    if [ $num_certificates == 0 ]; then
        echo "==== Installing a Let's Encrypt certificate (with CERTBOT_OPTS=$CERTBOT_OPTS)..."
        # Certbot will interactively prompt unless CERTBOT_OPTS is set.  For example:
        # CERTBOT_OPTS='--agree-tos --domains=mod9.io,www.mod9.io --email=ssl@mod9.co --eff-email'
        sudo certbot certonly --standalone $CERTBOT_OPTS
    elif [ $num_certificates == 1 ]; then
        echo "==== Found a Let's Encrypt certificate already installed:"
    else
        echo "ERROR: Certbot found an unexpected number of certificates: $num_certificates" >&2
        exit 1
    fi
    sudo certbot certificates &> /tmp/certbot-certificates.txt
    certbot_fullchain_path=$(grep 'Certificate Path:' /tmp/certbot-certificates.txt | sed 's,.*: ,,')
    certbot_privkey_path=$(grep 'Private Key Path:' /tmp/certbot-certificates.txt | sed 's,.*: ,,')

    # Overwrite the Apache SSL config.
    echo "# Let's Encrypt certificate managed by Certbot:" > $APACHE_SSL_CONFIG
    echo "SSLCertificateFile $certbot_fullchain_path" >> $APACHE_SSL_CONFIG
    echo "SSLCertificateKeyFile $certbot_privkey_path" >> $APACHE_SSL_CONFIG
    echo "INFO: Configured Apache to use the Certbot certificate."
    echo "SSL Certificate:        $certbot_fullchain_path"
    echo "SSL Private Key:        $certbot_privkey_path"
    echo

    # Schedule twice daily renewal of the certificate, via the Certbot Apache plugin.
    # This should be done via cron -- which usually isn't running in a Docker container.
    # TODO: convert this to a properly daemonized service, or run in a Docker container with init?
    echo "==== Scheduling renewal process with Certbot using Apache plugin..."
    while true; do sudo certbot -q renew --apache; sleep 43200; done &
    echo "Certbot Renewal PID:    $!"
    echo "Certbot Log:            /var/log/letsencrypt/letsencrypt.log"
fi
echo

# Enable an Apache site configuration that will:
# - serve static documentation and audio files;
# - run the REST API (process-internal via Flask/WSGI);
# - proxy the WebSocket server, running at ws://localhost:9980;
# - load SSL certificates and listen on TCP port 443 (and redirect port 80).
sudo a2ensite mod9-asr-ssl > /dev/null  # Hide confusing/misleading messages.

# Start web services in background, run ASR Engine in foreground with passed arguments.
exec www-engine $@
