#!/bin/bash

operate_usage() {
  if [ -n "$1" ]
  then
    echo "Error:" "$@" >&2
  fi

  echo "usage: $0 [operate method] -n name -i instance" >&2
  exit 1
}

# TODO: set ulimit
# TODO: set umask
# TODO: change group newgrp/sg
run_control() {
  local method=$1; shift
  local name=$1; shift
  local instance=$1; shift

  assert_is_instance operate_usage "$name" "$instance"

  (
    cd $name/$instance
    APPSH_INSTANCE_HOME=`pwd`
    cd current

    bin=`get_conf $BASEDIR $name $instance app.method`

    if [ -z "$bin" ]
    then
      bin=$APPSH_HOME/.app/lib/pid-method
    fi

    if [ ! -x "$bin" ]
    then
      echo "Invalid executable: $bin" >&2
      exit 1
    fi

    e="`get_conf_in_group $BASEDIR $name $instance env`"

    # Set a default PATH which can be overridden by the application's settings
    set +e
    env -i \
      PATH=/bin:/usr/bin \
      $e \
      APPSH_METHOD=$method \
      APPSH_BASEDIR=$BASEDIR \
      APPSH_HOME=$APPSH_HOME \
      APPSH_NAME=$name \
      APPSH_INSTANCE=$instance \
      APPSH_INSTANCE_HOME=$APPSH_INSTANCE_HOME \
      $bin
    local ret=$?
    set +x
    set -e

#    case $ret in
#      0)
#        echo "Method ${method} completed successfully for $name/$instance"
#        ;;
#      *)
#        echo "Error running method ${method} for $name/$instance"
#        ;;
#    esac
    exit $ret
  )
}

method_operate_usage() {
  if [ -n "$1" ]
  then
    echo "Error:" $@ >&2
  fi

  echo "usage: $0 operate <operate method>" >&2
  echo "" >&2
  echo "Available operate methods:" >&2
  echo "  start" >&2
  echo "  stop" >&2
  echo "  restart" >&2
  echo "  status" >&2
}

method_operate() {
  local name="$1"; shift
  local instance="$1"; shift
  local method="$1"

  if [ $# -gt 0 ]
  then
    shift
  fi

  case "$method" in
    start)   run_control "start" "$name" "$instance" "$@" ;;
    stop)    run_control "stop" "$name" "$instance" "$@" ;;
    status)  run_control "status" "$name" "$instance" "$@" ;;
    restart) run_control "restart" "$name" "$instance" "$@" ;;
    *)
      if [ -z "$method" ]
      then
        method_operate_usage
      else
        method_operate_usage "Unknown method $method"
      fi
      ;;
  esac
  exit $?
}