#!/bin/bash
# Copyright (c) 2018 Chris Cromer
# Released under the 2-clause BSD license.
#
# This is an implementation of the systemd-sysusers command

sysusersver=0.4.7

usage() {
	printf "sysusers\n\n"

	printf "sysusers creates system users and groups, based on the file\n"
    printf "format and location specified in sysusers.d(5).\n\n"

	printf "Usage: /usr/bin/sysusers [OPTIONS...] [CONFIGFILE...]\n\n"

	printf "Options:\n"
	printf "  --root=root               All paths will be prefixed with the\n"
    printf "                            given alternate root path, including\n"
    printf "                            config search paths.\n"
	printf "  --replace=PATH            Don't run check in the package\n"
	printf "  --inline                  Treat each positional argument as a\n"
	printf "                            separate configuration line instead of a\n"
	printf "                            file name.\n"
	printf "  -h, --help                Print a short help text and exit.\n"
	printf "  --version                 Print a short version string and exit.\n"
}

TEMP=$(getopt -o "h" -l "root:,replace:,inline,help,version" -n "sysusers" -- "$@")
if [ $? -ne 0 ]; then
	usage
	exit 1;
fi

arguments=()
replace=''
version=0
inline=0
error=0
root=''
replace=''
eval set -- "${TEMP}"
unset TEMP

while true; do
	case "${1}" in
		-h|--help)
			usage
			exit 0;
			shift;
			;;
		--root)
			root="${2}"
			shift 2;
			;;
		--replace)
			replace="${2}"
			shift 2;
			;;
		--inline)
			inline=1
			shift;
			;;
		--version)
			version=1
			shift;
			;;
		--) args=("${@}"); shift; break;;
		*) break;;
	esac
done

source /usr/lib/opensysusers/common.sh

if [ ${version} -eq 1 ]; then
	echo "${sysusersver}"
	exit ${error};
fi

if [ ${#args[@]} -eq 0 ]; then
	get_conf_files
	get_conf_paths

	for file in ${sysusers_d}; do
		parse_file ${file}
	done
	exit ${error};
fi

if [ ${inline} -eq 0 ]; then
	for file in "${args[@]}"; do
		[ ${file} == '--' ] && continue
		for dir in ${sysusers_dirs}; do
			if [ -f "${dir}/${file}" ]; then
				parse_file "${dir}/${file}"
				break
			fi
		done
	done
	if [ "${replace}" != '' ]; then
		get_conf_files
		get_conf_paths

		for file in ${sysusers_d}; do
			parse_file ${file}
		done
	fi
	exit ${error};
else
	for string in "${args[@]}"; do
		parse_string "${string}"
	done
	if [ "${replace}" != '' ]; then
		get_conf_files
		get_conf_paths

		for file in ${sysusers_d}; do
			parse_file ${file}
		done
	fi
	exit ${error};
fi

exit ${error};
