#!/usr/bin/env bash
set -eo pipefail; [[ $DOKKU_TRACE ]] && set -x

case "$1" in
  delete)
    dokku apps:destroy $2
    ;;

  logs)
    [[ -z $2 ]] && echo "Please specify an app to run the command on" && exit 1
    [[ ! -d "$DOKKU_ROOT/$2" ]] && echo "App $2 does not exist" && exit 1
    APP="$2";

    if [[ -f "$DOKKU_ROOT/$APP/CONTAINER" ]]; then
      CONTAINER=$(<$DOKKU_ROOT/$APP/CONTAINER)
      if [[ $3 == "-t" ]]; then
        docker logs --follow $CONTAINER
      else
        docker logs $CONTAINER | tail -n 100
      fi
    else
      echo "Application's container not found"
    fi
    ;;

  run)
    [[ -z $2 ]] && echo "Please specify an app to run the command on" && exit 1
    [[ ! -d "$DOKKU_ROOT/$2" ]] && echo "App $2 does not exist" && exit 1
    APP="$2"; IMAGE="dokku/$APP"

    shift 2

    DOCKER_ARGS=$(: | pluginhook docker-args $APP)
    docker run -i -t $DOCKER_ARGS $IMAGE /exec "$@"
    ;;

  url)
    [[ -z $2 ]] && echo "Please specify an app to run the command on" && exit 1
    [[ ! -d "$DOKKU_ROOT/$2" ]] && echo "App $2 does not exist" && exit 1
    APP="$2";

    if [[ -f "$DOKKU_ROOT/$APP/URL" ]]; then
      echo $(< "$DOKKU_ROOT/$APP/URL")
    fi
  ;;

  version)
    cat "$DOKKU_ROOT/VERSION" || {
      echo "Unable to determine dokku's version" 2>&1
      exit 1
    }
    ;;

  help)
    cat && cat<<EOF
    logs <app> [-t]                                 Show the last logs for an application (-t follows)
    run <app> <cmd>                                 Run a command in the environment of an application
    url <app>                                       Show the URL for an application
    version                                         Print dokku's version
EOF
    ;;

  *)
    exit $DOKKU_NOT_IMPLEMENTED_EXIT
    ;;

esac
