#!/usr/bin/env bash

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

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

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

    pluginhook pre-delete $APP

    stop_and_remove_app_containers
    stop_and_remove_container $APP_PERSISTENT_NAMES
    remove_image "$IMAGE"

    pluginhook post-delete $APP
    ;;

  logs)
    verify_app_name "$2"

    if [[ $3 == "-t" ]]; 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
    ;;

  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" || {
      echo "Unable to determine dokku's version" 2>&1
      exit 1
    }
    ;;

  help)
    cat && cat<<EOF
    delete <app>                                    Delete an application
    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
    ;;

esac

