#!/bin/bash

function run () {
    user=$1
    shift
    docker exec -itu "${user}" frappe bash -c "$@"
}

if [[ $# -eq 0 ]]; then
    docker exec -it frappe bash
elif [[ "$1" == 'setup' ]]; then
    if [[ "$2" == 'docker' ]]; then
        if [[ "$3" == '--swarm-mode' ]]; then
            echo "Docker swarm mode is not currently supported"
        elif [[ "$3" == 'down' ]]; then
            docker-compose down
        elif [[ "$3" == 'stop' ]]; then
            docker-compose stop
        elif [[ "$3" == '-d' ]]; then
            docker-compose up -d
        else

            docker-compose up
        fi
    else
        IFS=" "
        run frappe "bench $*"
    fi
elif [[ "$1" == '-c' ]]; then
    shift
    user=$1
    shift
    run "$user" "$@"
elif [[ "$1" == '-h' ]]; then
    echo "$0 [-h] | [-c frappe|root command] | [setup hosts|docker [stop|down]] | [bench_command]"
    echo ""
    echo "$0 is a wrapper for the Frappe Bench tool, and is used like it. However, it extends the tool in a few places."
    echo "Usage:"
    echo "    $0 -h"
    echo "                Shows this help message"
    echo "    $0"
    echo "                Launches you into an interactive shell in the container as user frappe"
    echo "    $0 <command to send to bench>"
    echo "                Runs the bench command <command>, i.e. $0 new-site \"site1.local\" = bench new-site \"site1.local\""
    echo "    $0 setup docker [ -d | stop | down ]"
    echo "                Builds and starts the docker containers using \"docker-compose up\""
    echo "          -d      |   Run containers in a detatched mode"
    echo "          stop    |   Stops containers"
    echo "          down    |   Deletes containers and assosiatated files (other than the files in volumes)."
    echo "    $0 -c frappe | root <command to run>"
    echo "                Runs a command in the container, as the selected user"
else
    IFS=" "
    run frappe "bench $*"
fi
