#!/bin/sh -f
# SPDX-License-Identifier: GPL-2.0
#
# Copyright (c) 2000-2001 Silicon Graphics, Inc.  All Rights Reserved.
#

status=0
have_db=""
have_repair=""
opt_extflg=""			# -e
opt_force=""			# -f
opt_log2=""			# -j
opt_projid32bit=""		# -p
opt_get_label=""		# -l
opt_get_uuid=""			# -u
opt_set_label=""		# -L
set_label=""
opt_set_uuid=""			# -U
set_uuid=""
repair_tokens=""

USAGE="Usage: xfs_admin [-efjlpuV] [-c 0|1] [-L label] [-U uuid] device"

while getopts "efjlpuc:L:U:V" c
do
	case $c in
	c)	repair_tokens="$repair_tokens lazycount=$OPTARG"
		have_repair=1
		;;
	e)	opt_extflg=1
		have_db=1
		;;
	f)	opt_force=1
		have_db=1
		;;
	j)	opt_log2=1
		have_db=1
		;;
	l)	opt_get_label=1
		have_db=1
		;;
	L)	opt_set_label=1
		set_label=$OPTARG
		have_db=1
		;;
	p)	opt_projid32bit=1
		have_db=1
		;;
	u)	opt_get_uuid=1
		have_db=1
		;;
	U)	opt_set_uuid=1
		set_uuid=$OPTARG
		have_db=1
		;;
	V)	xfs_db -p xfs_admin -V
		status=$?
		exit $status
		;;
	\?)	echo $USAGE 1>&2
		exit 2
		;;
	esac
done
set -- extra "$@"
shift $OPTIND
device=$1

# We use a bunch of opt_* flags here instead of crafting argument strings
# directly in the getopts loop above. This is because passing such strings
# to eval could cause command injection.
#
# As we cannot use arrays in POSIX, instead we resort to using the positional
# parameters ($@). Before calling any of the xfs_* utilities we reset $@ to an
# empty set with "set --". Then, based on the flags parsed above, we append all
# necessary arguments. This way each argument is passed verbatim, without being
# re-parsed or word-split by the shell.
case $# in
	1)	if [ -n "$have_db" ]
		then
			set --
			[ -n "$opt_extflg" ] && set -- "$@" -c "version extflg"
			[ -n "$opt_force" ] && set -- "$@" -f
			[ -n "$opt_log2" ] && set -- "$@" -c "version log2"
			[ -n "$opt_get_label" ] && set -- "$@" -r -c label
			[ -n "$opt_set_label" ] && set -- "$@" -c "label $set_label"
			[ -n "$opt_projid32bit" ] && set -- "$@" -c "version projid32bit"
			[ -n "$opt_get_uuid" ] && set -- "$@" -r -c uuid
			[ -n "$opt_set_uuid" ] && set -- "$@" -c "uuid $set_uuid"
			xfs_db -x -p xfs_admin "$@" "$device"
			status=$?
		fi
		if [ -n "$have_repair" ]
		then
			# Hide normal repair output which is sent to stderr
			# assuming the filesystem is fine when a user is
			# running xfs_admin.
			# Ideally, we need to improve the output behaviour
			# of repair for this purpose (say a "quiet" mode).
			set --
			for token in $repair_tokens
			do
				set -- "$@" -c "$token"
			done
			xfs_repair "$@" "$device" 2> /dev/null
			status=`expr $? + $status`
			if [ $status -ne 0 ]
			then
				echo "Conversion failed, is the filesystem unmounted?"
			fi
		fi
		;;
	*)	echo $USAGE 1>&2
		exit 2
		;;
esac
exit $status
