#!/bin/bash

display_usage() {
  echo "$(basename "$0") [-h] [-c \"<command to be executed inside container>\"]"
  echo ''
  echo 'where:'
  echo '    -h  show this help text'
  echo '    -c  execute a command inside docker using docker exec'
  echo '    -s  adds site-names to /etc/hosts file in the container to facilitate multisite access'
}

# start docker containers if they are not running (check for frappe)
launch_containers() {
  docker exec frappe /bin/true 2>/dev/null
  if [[ $? -eq 1 ]]; then
    docker-compose up -d
  fi
}

if [[ $# -eq 0 ]]; then
  launch_containers
  docker exec -it frappe bash
else
  while getopts ':hsc:' option; do
    case "$option" in
      h)
         display_usage
         exit
         ;;
      c)
         launch_containers
         docker exec frappe bash -c "bench $OPTARG"
         ;;
      s)
         a=$(cd frappe-bench && ls sites/*/site_config.json | grep -o '/.\+/')
         a="${a//$'\n'/ }"
         a=$(echo $a | tr -d / )
         result="127.0.0.1 ${a}"
         echo $result
         docker exec -u root -i frappe bash -c "echo ${result} | tee --append /etc/hosts"
         ;;
      \?)
        echo "Invalid option: -$OPTARG" >&2
        exit 1
        ;;
      :)
        echo "Option -$OPTARG requires an argument." >&2
        exit 1
        ;;
    esac
  done
fi
