## Authors:
##   Ajrat Makhmutov <rauty@altlinux.org>
##
## Copyright (C) 2025  Basealt LLC
##
## This file is part of alterator-kopidel.
##
## alterator-kopidel is free software: you can redistribute it and/or modify it under the terms
## of the GNU General Public License as published by the Free Software Foundation,
## either version 3 of the License, or (at your option) any later version.
##
## alterator-kopidel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
## without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
## See the GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along with alterator-kopidel.
## If not, see <https://www.gnu.org/licenses/>.

if [ -n "${__included_kopidel_check_incoming_parameters-}" ]; then
	return 0
fi
readonly __included_kopidel_check_incoming_parameters=1

. alterator-sh-functions
. "${KOPIDEL_LIBDIR:-/usr/lib/alterator-kopidel}/variables"

fast_check_in_workdir() (
	if [[ -z "$in_workdir" || "$in_workdir" == "no_available" ]]; then
		echo "The workdir variable is not specified." >&2
		return 1
	fi
	if [[ ! -d "$in_workdir" ]]; then
		echo "The workdir variable is not a directory path." >&2
		return 2
	fi
	if [[ $(basename "$in_workdir") != "$WORKDIR_NAME" ]]; then
		echo "Basename of workdir is not $WORKDIR_NAME." >&2
		return 3
	fi
	workdir_mountpoint="$(realpath "$in_workdir" | sed "s/$WORKDIR_NAME\$//")"
	if ! "$KOPIDEL_LIBEXECDIR/check-fs-features.sh" "$workdir_mountpoint"; then
		echo "The fs of the workdir_mountpoint $workdir_mountpoint is bad." >&2
		return 4
	fi
)

fast_check_in_exdrive() (
	if [[ -z "$in_exdrive" || "$in_exdrive" == "no_available" ]]; then
		echo "The exdrive variable is not specified." >&2
		return 1
	fi
	if [[ ! -e "$in_exdrive" ]]; then
		echo "The exdrive $in_exdrive variable is not exists." >&2
		return 2
	fi
	if [[ "$(lsblk -dno TYPE "$in_exdrive")" != disk ]]; then
		echo "The exdrive $in_exdrive variable is not a disk." >&2
		return 3
	fi
	( mount | grep "$in_exdrive" | while read -r mnt_line; do
		mnt_name="$(echo "$mnt_line" | cut -d ' ' -f 1)"
		mnt_dir="$( echo "$mnt_line" | cut -d ' ' -f 3)"
		# Automounted, mounted by user not system drives in GNOME.
		if [[ "$mnt_dir" == /run/media/* ]]; then
			continue
		fi
		# Exdrive is currently used by kopidel.
		if [[ "$(realpath "$mnt_dir")" == "$EXDRIVE_WORKDIR"/* ]]; then
			continue
		fi
		if [[ "$(lsblk --paths -ndo pkname "$mnt_name")" == "$in_exdrive" || "$mnt_name" == "$in_exdrive" ]]; then
			echo "The exdrive $in_exdrive has a non-automount mountpoint: $mnt_dir" >&2
			exit 1
		fi
	done ) || return 4
)
