#!/usr/bin/env bash

source "$(dirname $0)/../dokku_common"

case "$1" in
  apps:list)
    verify_max_args 1 "$@"
    for app in $(ls -d $DOKKU_ROOT/*/ 2>/dev/null); do
      if [[ -f "$app/refs/heads/master" ]]; then
        basename "$app"
      fi
    done
    ;;

  apps:status)
    verify_app_name "$2"
    verify_max_args 2 "$@"

  	if docker port "$APP_NAME" "$APP_PORT" 1>/dev/null 2>/dev/null
  	then
  		echo "$APP is running."
  	else
  		echo "$APP is stopped."
  	fi
	;;

  apps:start)
    verify_app_name "$2"
    verify_max_args 2 "$@"
    
    docker start "$APP_NAME"
	;;

  apps:stop)
    verify_app_name "$2"
    verify_max_args 2 "$@"
    
    docker stop "$APP_NAME"
	;;

  apps:disable)
    verify_app_name "$2"
    verify_max_args 2 "$@"
    if [[ ! -f "$APP_DIR/DISABLED" ]]; then
      touch "$APP_DIR/DISABLED"
      deploy_app "$APP"
    else
      echo "$APP: Application is already disabled"
    fi
  ;;

  apps:enable)
    verify_app_name "$2"
    verify_max_args 2 "$@"
    if [[ -f "$APP_DIR/DISABLED" ]]; then
      rm -f "$APP_DIR/DISABLED"
      deploy_app "$APP"
    else
      echo "$APP: Application is already enabled"
    fi
  ;;

  apps:restart)
    verify_app_name "$2"
    verify_max_args 2 "$@"
    docker restart "$APP_NAME"
    ;;

  apps:top)
    verify_app_name "$2"
    verify_max_args 2 "$@"
    
    shift 2
    docker top "$APP_NAME"
    ;;

  help)
    cat && cat<<EOF
    apps:list                 List app
    apps:status <app>         Status of specific app
    apps:start <app>	        Stop specific app
    apps:stop <app>		        Stop specific app
    apps:restart <app>        Restart specific app (not-redeploy)
    apps:enable <app>         Re-enable specific app
    apps:disable <app>        Disable specific app
    apps:top <app> [args...]  Show running processes
EOF
    ;;
esac
