#!/bin/sh

show_help() {
    cat <<EOF
Usage: lockbox [options]
Options:
    --production    Run in production mode (default: development mode)

EOF
}

lockbox_mode=development

# Parse command line options
while true; do
    case "$1" in
      -h|--help|-\?) show_help; exit 0;;
      --production) lockbox_mode=production; shift ;;
      --development) shift ;;
      --) shift; break;;
      -*) echo "invalid option: $1" 1>&2; show_help; exit 1;;
      *)  break;;
    esac
done

# If our dependencies are installed in the source tree, find them there
. scripts/use-deps.sh

# Make sure we have some API keys, otherwise we can't do much
apikeys=Config/apikeys.json
if [ ! -f "$apikeys" ]; then
    echo "No API keys found in $apikeys" >&2
    echo "see https://github.com/sxux/LockBox/wiki/GettingAPIKeys" >&2
    exit 1
fi

cleanup_mongo() {
    mongodata=Me/mongodata
    mongolock=$mongodata/mongod.lock
    if [ -s $mongolock ]; then
        echo "mongod lock file exists: $mongolock..."
        pid=$(cat "$mongolock")
        if [ "$lockbox_mode" = "production" ]; then
            # Shut it down
            echo "Shutting down mongod."
            kill "$pid"
            while kill -0 "$pid" >/dev/null 2>&1; do
                echo "Waiting for mongod to exit..."
                sleep 1
            done
            echo "mongod shut down."
        else
            # Automatically check and repair mongo
            if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
                echo "...and it's still running.  Hopefully that's OK."
            else
                echo "...but it's dead.  Cleaning up..."
                rm -f "$mongolock"
                if ! mongod --dbpath "$mongodata" --repair; then
                    echo "mongod --repair failed!" >&2
                    exit 1
                fi
            fi
        fi
    fi
}

monitor() {
    # Monitor the process and restart it if it dies

    trap shutdown INT TERM
    while true; do
        start_time=$(date +%s)
        # start the command
        $* &
        lockboxd_pid=$!

        if wait $lockboxd_pid; then
            # Clean shutdown
            exit 0
        fi

        # Abnormal exit
        cleanup_mongo

        end_time=$(date +%s)
        runtime=$(($end_time - $start_time))
        if [ "$runtime" -lt 10 ]; then
            echo "lockbox was only running for $runtime seconds, not respawning" >&2
            exit 1
        fi

        wait=5
        echo "lockbox exited unexpectedly, respawning in $wait seconds..." >&2
        sleep $wait
    done
}

shutdown() {
    kill -TERM $lockboxd_pid
    wait $lockboxd_pid
    status=$?
    echo "lockbox exited with status $status"
    cleanup_mongo
    exit $status
}

cleanup_mongo

# Extra paths to search for files : separated
export NODE_PATH=Common/node:node_modules

#export HTTP_PROXY=http://www-proxy.ericsson.se:8080
#export HTTPS_PROXY=http://www-proxy.ericsson.se:8080
#export NO_PROXY="localhost,127.0.0.1/8,.local"

# Start the lockbox
#nave use 0.6.11
case "$lockbox_mode" in
    production)
        # Tell node to run in production mode
        NODE_ENV=production
        export NODE_ENV
        monitor node lockboxd.js "$@"
        ;;
    development|*)
        # Just run it
        exec node lockboxd.js "$@"
        ;;
esac

exit 1
