#!/sbin/openrc-run
# Copyright 2018 Márcio Silva <coadde@hyperbola.info>
# Released under the 2-clause BSD license

# don't lose variables
set -a

description="OS level virtualization from chroot command"

[[ -z $CR_COMD ]] && CR_COMD=/sbin/init
CR_PIDF=/run/chroot.$CR_NAME.pid

depend() {
	need $CR_DEPS
	after modules bootmisc localmount net netmount
	keyword -jail -prefix -vserver
	provide oslv
}

start() {
	ebegin "Start $CR_NAME chroot virtualization"
	case $RC_UNAME in
		GNU/Linux|Linux)
			# uses linux namespaces (unshare) to isolate the CR_COMD command
			chroot $CR_PATH /sbin/unshare \
				--cgroup \
				--fork \
				--ipc \
				--mount \
				--net \
				--pid \
				--propagation private \
				--setgroups allow \
				--uts \
				-- \
				$CR_COMD &
			eend $?
			;;
		*)
			chroot $CR_PATH $CR_COMD &
			eend $?
			;;
	esac
	# wait in seconds to run CR_COMD
	sleep $CR_CDWT
	# save the CR_COMD PID to a pid file
	pgrep -n ${CR_COMD##*/} > $CR_PIDF
	case $RC_UNAME in
		GNU/Linux|Linux)
			# isolate network interfaces to chroot command (only with linux kernel)
			if [[ $CR_NINF ]]; then
				for int in $CR_NINF; do
					einfo "Add $int to chroot.$CR_NAME"
					ip link set $int netns $(cat $CR_PIDF)
					eend $?
				done
				unset int
			fi
			if [[ $CR_WINF ]]; then
				for wif in $CR_WINF; do
					einfo "Add $wif to chroot.$CR_NAME"
					iw phy $wif set netns $(cat $CR_PIDF)
					eend $?
				done
				unset wif
			fi
			;;
	esac
	einfo "wait in seconds to start the service"
	sleep ${CR_STWT:-1}
	eend $?
}

stop() {
	ebegin "Stop $CR_NAME chroot virtualization"
	# use SIGINIT or 2 to stop the CR_COMD
	if (( $(cat $CR_PIDF) != 1 )); then
		kill -s 2 $(cat $CR_PIDF) && rm $CR_PIDF
	fi
	einfo "wait in seconds to stop the service"
	sleep ${CR_SPWT:-1}
	eend $?
}
