#!/bin/bash
# Installed as /usr/sbin/mcc, the single admin command of the MCC package.
#
#   sudo mcc deploy                 configure the host and start the MCC timers
#   sudo mcc uninstall [options]    remove the MCC runtime (see: mcc uninstall --help)
#   sudo mcc collect-diagnostics [options]
#                                   write a redacted support bundle
#
# Each subcommand execs the matching script in /usr/lib/mcc with the remaining
# arguments. The target is checked the same way the scripts check
# utilities.sh before it is run: no symlink, root-owned, not writable by others.
set -o pipefail
umask 077
PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH

lib=/usr/lib/mcc

usage()
{
	printf '%s\n' \
		"Usage: sudo mcc <command> [options]" \
		"" \
		"Commands:" \
		"  deploy                 Configure the host from /var/lib/mcc/mcc.env and start the MCC timers." \
		"  uninstall              Remove the MCC runtime (mcc uninstall --help for options)." \
		"  collect-diagnostics    Write a redacted support bundle (mcc collect-diagnostics --help)." \
		"  help                   Show this help."
}

if [ "$#" -eq 0 ]; then
	usage >&2
	exit 2
fi

cmd="$1"
shift
case "$cmd" in
	deploy)              target="$lib/deploymcc.sh" ;;
	uninstall)           target="$lib/uninstallmcc.sh" ;;
	collect-diagnostics) target="$lib/collectmccdiagnostics.sh" ;;
	help|-h|--help)      usage; exit 0 ;;
	*)
		printf 'mcc: unknown command: %s\n' "$cmd" | tr -d '\000-\010\013-\037\177' >&2
		usage >&2
		exit 2
		;;
esac

if [ "$(id -u)" -ne 0 ]; then
	printf 'mcc: must be run as root (sudo mcc %s).\n' "$cmd" >&2
	exit 1
fi

if [ -L "$lib" ] || [ -L "$target" ] \
	|| [ "$(find "$lib" -maxdepth 0 -type d -user 0 ! -perm /022 -print 2>/dev/null)" != "$lib" ] \
	|| [ "$(find "$target" -maxdepth 0 -type f -user 0 ! -perm /022 -print 2>/dev/null)" != "$target" ]; then
	printf 'mcc: %s is missing or modifiable by non-root users; reinstall the microsoft-connected-cache package, exiting.\n' "$target" >&2
	exit 91
fi

exec /bin/bash -- "$target" "$@"
