#!/bin/sh
#
# Script to install OpenWorkouts for development
#

# Full path to where we run the script from
current=`pwd`
# Full path to the main python binary (will be set by check_python3())
python_bin=''
# Full path to the env
env_path=${current}/env
# full path to the install logs
install_log=${current}/var/log/install.log
# mail queue directory (where automatically generated emails are stored)
mail_queue_path=${current}/var/spool/mqueue

set_scripts_permissions() {
    echo "Setting up script permissions"
    # ensure the shell scripts we will need have proper permissions
    chmod u+x ${current}/bin/js_deps
    chmod u+x ${current}/bin/start
}

check_python3() {
    # if python3 is not installed, exit with an error
    if command -v python3 > /dev/null; then
        # ok
        python_bin=`command -v python3`
        echo "Found valid python installation: ${python_bin}"
        return
    else
        # no python3 binary, look for python
        if command -v python > /dev/null; then
            # python found, check if it is 3.x
            if `command -v python` -c "import sys; exit(0) if sys.version.startswith('3.') else exit(1)"; then
                python_bin=`command -v python`
                echo "Found valid python installation: ${python_bin}"
                return
            else
                # no python binary, error
                echo "Error: could not find a suitable python version installed, please install python 3.x"
                exit 1
            fi
        else
            # no python binary, error
            echo "Error: could not find a suitable python version installed, please install python 3.x"
            exit 1
        fi
    fi
}

create_venv() {
    # create a new virtual environment
    if [ ! -d ${env_path} ]; then
        echo "Creating new python virtual environment [${env_path}]"
        ${python_bin} -m venv ${env_path}
    else
        if [ ! -f ${env_path}/bin/activate ]; then
            # env dir found, but not a virtual env
            echo "Error: ${env_path} exists and is not a valid virtual environment"
            exit 1
        else
            echo "Reusing python virtual environment [${env_path}]"
        fi
    fi
}

upgrade_pip_setuptools() {
    . ${env_path}/bin/activate
    echo "Upgrading python packaging tools"
    yes | pip install --upgrade setuptools pip >> ${install_log}.stdout 2>> ${install_log}.stderr
    deactivate
}

install_openworkouts() {
    . ${env_path}/bin/activate
    echo "Installing OpenWorkouts dependencies"
    yes | pip install --upgrade -e ${current}[testing] >> ${install_log}.stdout 2>> ${install_log}.stderr
    deactivate
}

install_js_deps() {
    echo "Installing javascript components"
    ${current}/bin/js_deps >> ${install_log}.stdout 2>> ${install_log}.stderr
}

create_mail_queue() {
    # Creates a Maildir-format directory that pyramid_mailer can use to
    # queue mails.
    echo "Creating mail spool directory ${mail_queue_path}"
    mkdir -p ${mail_queue_path}/new >> ${install_log}.stdout 2>> ${install_log}.stderr
    mkdir -p ${mail_queue_path}/tmp >> ${install_log}.stdout 2>> ${install_log}.stderr
    mkdir -p ${mail_queue_path}/cur >> ${install_log}.stdout 2>> ${install_log}.stderr
}

setup_mail_server() {
    echo ""
    echo "IMPORTANT, READ BEFORE STARTING OpenWorkouts"
    echo "--------------------------------------------"
    echo ""
    echo "For emails to be sent by OpenWorkouts you have to set up your mail"
    echo "server account. Edit the file development.ini and update the"
    echo "parameters:"
    echo ""
    echo "  mail.host = SERVER"
    echo "  mail.tls = True"
    echo "  mail.username = USERNAME"
    echo "  mail.password = PASSWORD"
    echo ""
    echo "--------------------------------------------"

}

create_cron_job() {
    echo ""
    echo "IMPORTANT, READ BEFORE STARTING OpenWorkouts"
    echo "--------------------------------------------"
    echo ""
    echo "Remember to add a periodic task in your operating system to process"
    echo "the mail queue, so emails are sent"
    echo ""
    echo "In a unix-like system, add this to your crontab:"
    echo ""
    echo "*/5 * * * * cd ${current} && ./bin/send_emails > /dev/null 2> /dev/null"
    echo ""
    echo "--------------------------------------------"
    echo ""
}

setup_start_stop() {
    echo "OpenWorkouts successfully installed in ${env_path}"
    echo ""
    echo "You can now start the OpenWorkouts service calling:"
    echo ""
    echo "  cd ${current} && ./bin/start"
    echo ""
    echo "(the installation script left a log under ${install_log})"
    echo ""
    # echo "You can stop any running OpenWorkouts instances calling:"
    # echo ""
    # echo "  ${current}/bin/stop"
    # echo ""
}

set_scripts_permissions
check_python3
create_venv
upgrade_pip_setuptools
install_openworkouts
install_js_deps
create_mail_queue
setup_mail_server
create_cron_job
setup_start_stop
