#! /bin/bash
#########################################################################
#									#
#	lxcu-attach is automatically generated,				#
#		please do not modify!					#
#									#
#########################################################################

#########################################################################
#									#
# Author: Copyright (C) 2022, 2024, 2025  Mark Grant			#
#									#
# Released under the GPLv3 only.					#
# SPDX-License-Identifier: GPL-3.0-only					#
#									#
# Purpose:								#
# A wrapper script for lxc-attach utilising systemd-run to support	#
# unprivileged containers.						#
#									#
# Syntax:	See usage()						#
#									#
# Exit codes used:-							#
# Bash standard Exit Codes:	0 - success				#
#				1 - general failure			#
# User-defined exit code range is 64 - 113				#
#	C/C++ Semi-standard exit codes from sysexits.h range is 64 - 78	#
#		EX_USAGE	64	command line usage error	#
#		EX_DATAERR	65	data format error		#
#		EX_NOINPUT	66	cannot open input		#
#		EX_NOUSER	67	addressee unknown		#
#		EX_NOHOST	68	host name unknown		#
#		EX_UNAVAILABLE	69	service unavailable		#
#		EX_SOFTWARE	70	internal software error		#
#		EX_OSERR	71	system error (e.g., can't fork)	#
#		EX_OSFILE	72	critical OS file missing	#
#		EX_CANTCREAT	73	can't create (user) output file	#
#		EX_IOERR	74	input/output error		#
#		EX_TEMPFAIL	75	temp failure; user is invited	#
#					to retry			#
#		EX_PROTOCOL	76	remote error in protocol	#
#		EX_NOPERM	77	permission denied		#
#		EX_CONFIG	78	configuration error		#
#	User-defined (here) exit codes range 79 - 113:			#
#		None							#
#									#
# Further Info:								#
#									#
#########################################################################


set -o pipefail


##################
# Init variables #
##################
readonly version=1.2.0				# Script version
readonly packageversion=1.3.4		# Package version

# Ensure environment variables are set.
export XDG_RUNTIME_DIR="/run/user/$UID"
export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus"

configcli_extra_args=""


#############
# Functions #
#############

# -h --help output.
# No parameters
# No return value
usage()
{
cat << EOF
Usage is:-
$(basename "$0") {-h|-V}
$(basename "$0") CONTAINER_NAME CONTAINER_COMMAND
Usage is:-
$(basename "$0") [options]
	-h or --help Display this help information
	-V or --version Print script version information
	Optional command to run in the container
EOF
}

# Standard function to emit messages depending on various parameters.
# Parameters -	$1 What:-	The message to emit.
#		$2 Where:-	stdout == 0
#				stderr == 1
# No return value.
output()
{
	if (( !$2 )); then
		printf "%s\n" "$1"
	else
		printf "%s\n" "$1" 1>&2
	fi
}

# Standard function to tidy up and return exit code.
# Parameters - 	$1 is the exit code.
# No return value.
script_exit()
{
	exit "$1"
}

# Standard function to test command error and exit if non-zero.
# Parameters - 	$1 is the exit code, (normally $? from the preceeding command).
# No return value.
std_cmd_err_handler()
{
	if (( $1 )); then
		script_exit "$1"
	fi
}

# Standard trap exit function.
# No parameters.
# No return value.
# shellcheck disable=SC2317  # Do not warn about unreachable commands in trap
# functions, they are legitimate.
trap_exit()
{
	local -i exit_code=$?
	local msg

	msg="Script terminating with exit code $exit_code due to trap received."
	output "$msg" 1
	std_cmd_err_handler "$exit_code"
}

# Setup trap
trap trap_exit SIGHUP SIGINT SIGQUIT SIGTERM

# Process command line arguments with GNU getopt.
# Parameters -	$1 is the command line.
# No return value.
proc_CL()
{
	local GETOPTTEMP
	local msg
	local tmp

	tmp="getopt -o hV --long help,version"
	GETOPTTEMP=$($tmp -n "$0" -- "$@")
	std_cmd_err_handler $?

	eval set -- "$GETOPTTEMP"
	std_cmd_err_handler $?

	while true; do
		case "$1" in
		-h|--help)
			usage
			shift
			script_exit 0
			;;
		-V|--version)
			printf "%s Script version %s\n" "$0" $version
			printf "%s Package version %s\n" "$0" $packageversion
			shift
			script_exit 0
			;;
		--)	shift
			break
			;;
		*)	output "Internal error." 1
			std_cmd_err_handler 64
			;;
		esac
	done

	if (( $# >= 1 )); then
		name=$1
		shift
	fi

	# Container name must be specified.
	if [[ -z $name ]]; then
		output "Container name must be specified." 1
		std_cmd_err_handler 64
	fi

	# Container must exist and must be running.
	if (( ! $(lxc-ls -1 --filter="^$name$" | wc -l) )); then
		output "Container $name must exist." 1
		std_cmd_err_handler 64
	fi
	if (( $(lxc-ls -1 --stopped --filter="^$name$" | wc -l) )); then
		output "Container $name must be running." 1
		std_cmd_err_handler 64
	fi

	# Remaining arguments are passed straight to the lxc-attach command
	# line. This must be inputised before being passed on in order to
	# maintain original quoting. It can then be 'eval'ed.
	if (( $# )); then
		# This works as intended so silence shellcheck warning.
		# shellcheck disable=SC2124
		configcli_extra_args=${@@Q}
	fi
}


########
# Main #
########

proc_CL "$@"

cmd="systemd-run --quiet --user --scope --property \"Delegate=yes\""
cmd+=" -- lxc-attach -n $name $configcli_extra_args"
eval "$cmd"
std_cmd_err_handler $?

# And exit.
script_exit 0

