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

trigger-storage-install() {
  declare desc="storage install trigger"
  declare trigger="install"

  mkdir -p "${DOKKU_LIB_ROOT}/data/storage"
  chown "${DOKKU_SYSTEM_USER}:${DOKKU_SYSTEM_GROUP}" "${DOKKU_LIB_ROOT}/data/storage"

  STORAGE_SUDOERS_FILE="/etc/sudoers.d/dokku-storage"
  local mode="0440"
  case "$DOKKU_DISTRO" in
    arch | debian | raspbian | ubuntu)
      echo "%dokku ALL=(ALL) NOPASSWD:$PLUGIN_AVAILABLE_PATH/storage/bin/chown-storage-dir *" >"$STORAGE_SUDOERS_FILE"
      echo "Defaults env_keep += \"DOKKU_LIB_ROOT\"" >>"$STORAGE_SUDOERS_FILE"
      ;;
  esac

  chmod "$mode" "$STORAGE_SUDOERS_FILE"
}

trigger-storage-install "$@"
