#!/usr/bin/env bash

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

case "$1" in
  logs)
    verify_app_name "$2"

    if [[ $3 == "-t" ]] || [[ $3 == "-f" ]]; then
      docker logs --follow "$APP_NAME"
    else
      docker logs "$APP_NAME" | tail -n 100
    fi
    ;;

  run)
    verify_app_name "$2"

    if [[ ! -d "$DOKKU_ROOT/$APP" ]]; then
        echo "App $APP does not exist"
        exit 1
    fi
    shift 2

    stop_and_remove_app_containers "run" >/dev/null

    DOCKER_ARGS=$(: | pluginhook docker-args $APP run)

    if is_image_buildstep_based "$IMAGE"; then
      # buildstep
      docker run --cidfile="$(get_cid_file_name run)" --rm --name="$(get_app_container_name run)" -i -t $DOCKER_ARGS "$IMAGE" /exec "$@"
    else
      # Dockerfile
      docker run --cidfile="$(get_cid_file_name run)" --rm --name="$(get_app_container_name run)" --env-file=<(: | pluginhook env-vars "$APP") --entrypoint="/bin/bash" -i -t $DOCKER_ARGS "$IMAGE" -c "$@"
    fi
    ;;

  enter)
    verify_app_name "$2"
    verify_max_args 2 "$@"

    [[ "$APP_NAME" == "" ]] && fail "$APP: application not running"

    if is_image_buildstep_based "$IMAGE"; then
      # buildstep
      docker exec -i -t "$APP_NAME" /exec /bin/bash
    else
      # dockerfile
      docker exec -i -t "$APP_NAME" /bin/bash
    fi
    ;;

  exec)
    verify_app_name "$2"
    shift 2

    [[ "$APP_NAME" == "" ]] && fail "$APP: application not running"

    if is_image_buildstep_based "$IMAGE"; then
      # buildstep
      docker exec "$APP_NAME" /exec "$@"
    else
      # dockerfile
      docker exec "$APP_NAME" "$@"
    fi
    ;;

  url)
    verify_app_name "$2"

    if [[ ! -d "$DOKKU_ROOT/$APP" ]]; then
        echo "App $APP does not exist"
        exit 1
    fi

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

  version)
    cat "$(dirname $0)/../../VERSION" 2>/dev/null || {
      echo "Unable to determine dokku's version" 2>&1
      exit 1
    }
    ;;

  help)
    cat && cat<<EOF
    delete <app>                                    Delete an application
    logs <app> [-t] [-f]                            Show the last logs for an application (-t or -f follows)
    run <app> <cmd>                                 Run a command in the environment of an application
    enter <app>                                     Enter into currently running container
    exec <app> <cmd>                                Execute command in currently running container
    url <app>                                       Show the URL for an application
    version                                         Print dokku's version
EOF
    ;;

  *)
    exit $DOKKU_NOT_IMPLEMENTED_EXIT
    ;;

esac
