#!/usr/bin/env zsh
#####################################################################

DEPENDENCIES+=(jq umount sudo)
REQUIRED_ENV+=(AWS__EFS__LOCAL_MOUNT_POINT)

#####################################################################

USAGE__description='
	interactively unmount an AWS EFS volume to the local filesystem
'

MAIN() {
	eval "$(utils.parse.autosetup)"
	##########################################

	[[ -d "${AWS__EFS__LOCAL_MOUNT_POINT}" ]] || {
		echo.status 'no efs currently mounted'
		return 0
	}

	local MOUNTED=$(cd -- "${AWS__EFS__LOCAL_MOUNT_POINT}" && find . -type f | sed 's|^\./||')
	[[ "${MOUNTED}" ]] || {
		echo.status 'no efs currently mounted'
		return 0
	}

	utils.io.getsudo || return 1

	local SELECTED=$(echo ${MOUNTED} | utils.fzf 'select a file system to unmount')
	[ "${SELECTED}" ] || echo.error.user-abort || return 1

	local EFS="${AWS__EFS__LOCAL_MOUNT_POINT}/${SELECTED}"
	echo.status "unmounting '${SELECTED}'"
	sudo umount "${EFS}" &>/dev/null
	sudo rmdir -- "${EFS}" \
		&& echo.success "done" \
		|| echo.error "failed to unmount '${EFS}'"
}
