#!/usr/bin/env bash
[[ " storage storage:list storage:mount storage:unmount storage:help help " == *" $1 "* ]] || exit "$DOKKU_NOT_IMPLEMENTED_EXIT"
set -eo pipefail; [[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_CORE_AVAILABLE_PATH/storage/functions"
source "$PLUGIN_CORE_AVAILABLE_PATH/docker-options/functions"

case "$1" in
  storage:list)
    # List all bound mounts
    passed_phases="deploy"
    [[ ! $2 ]] && dokku_log_fail "storage:list requires an app to list."
    verify_app_name "$2" && APP="$2"
    echo "$APP volume bind-mounts:"
    get_bind_mounts "$(get_phase_file_path "$passed_phases")"
    ;;

  storage:mount)
    # Add bind-mount, redeploy app if running
    passed_phases=(deploy run)
    [[ -z $3 || $4 ]] && dokku_log_fail "storage:mount requires an app and a two paths devided by colon."
    verify_app_name "$2" && APP="$2"
    verify_paths "$3" && MOUNT_PATH="$3"
    check_if_path_exists "$MOUNT_PATH" "$(get_phase_file_path "${passed_phases[@]}")" && dokku_log_fail "Mount path already exists."
    add_passed_docker_option passed_phases[@] "-v $MOUNT_PATH"
    ;;

  storage:unmount)
    # Remove bind-mount, restart app if running
    passed_phases=(deploy run)
    [[ -z $3 || $4 ]] && dokku_log_fail "storage:unmount requires an app and a two paths devided by colon."
    verify_app_name "$2" && APP="$2"
    verify_paths "$3" && MOUNT_PATH="$3"
    check_if_path_exists "$MOUNT_PATH" "$(get_phase_file_path "${passed_phases[@]}")" || dokku_log_fail "Mount path does not exist."
    remove_passed_docker_option passed_phases[@] "-v $MOUNT_PATH"
    ;;

  help | storage:help)
    cat<<EOF
    storage:list <app>, List bind mounts for app's container(s) (host:container)
    storage:mount <app> <host-dir:container-dir>, Create a new bind mount
    storage:unmount <app> <host-dir:container-dir>, Remove an existing bind mount
EOF
    ;;

  *)
    exit "$DOKKU_NOT_IMPLEMENTED_EXIT"
    ;;

esac
