#!/bin/sh -efu
#
# Copyright (C) 2023 Evgeny Sinelnikov <sin@altlinux.org>,
#
# The distro_check utility functions.
#
# This file 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

unset \
	LANG \
	LANGUAGE \
	LINGUAS \
	LC_CTYPE \
	LC_NUMERIC \
	LC_TIME \
	LC_COLLATE \
	LC_MONETARY \
	LC_MESSAGES \
	LC_PAPER \
	LC_NAME \
	LC_ADDRESS \
	LC_TELEPHONE \
	LC_MEASUREMENT \
	LC_IDENTIFICATION \
	LC_ALL \
	||:

PROG="${0##*/}"

Info()
{
	printf %s\\n "$PROG: $*" >&2
}

Fatal()
{
	printf %s\\n "$PROG: $*" >&2
	exit 1
}

quiet=
Message()
{
	[ -z "$quiet" ] || return 0
	printf %s\\n "$*"
}

Warning()
{
	[ -z "$quiet" ] || return 0
	printf %s\\n "$*" >&2
}

show_bad_files=
FileError()
{
	local text="$1"
	shift || return
	local f="${1-}"

	if [ -n "$f" ]; then
		text="${text#$f: }"
		text="$f: $text"
		[ -z "$show_bad_files" ] || printf %s\\n "$f"
	fi
	printf %s\\n "$(printf %s "$text" |tr '[:cntrl:]' ' ')" >&2
}

CheckError()
{
	Message "$PROG: ${check:+check-${check#*-check-} }ERROR: $*"
}

work_dir=
cleanup()
{
	trap - EXIT
	[ -z "$work_dir" ] || rm -rf -- "$work_dir"
	exit "$@"
}

exit_handler()
{
	cleanup $?
}

signal_handler()
{
	cleanup 1
}

init_check()
{
	[ -z "$work_dir" ] || return 0

	trap exit_handler EXIT
	trap signal_handler HUP PIPE INT QUIT TERM
	work_dir="$(mktemp -d -t "$PROG.XXXXXXXXXX")"
}

distro_type=
get_distro_type()
{
	local file header

	distro_type=
	file="$1" && shift
	mime="$(file -b --mime-type "$file")" || return
	case "$mime" in
	'application/x-iso9660-image')
		distro_type=iso
		return 0
		;;
	esac
	return 1;
}

oneliner()
{
	printf %s "$*" |tr -s '[:space:]' ' '
}
