#!/bin/sh

MODE="normal"
SESSION="$(id -un)"
INTERNET_ACCESS=""

# -------------- Argument Parsing --------------

while [ $# -gt 0 ]; do
	case "$1" in
	
	--mode)
		MODE="$2"
		shift 2
		;;

	--session-name)
		SESSION="$2"
		shift 2
		;;
	
	--internet-access)
		if [ $2 == 1 || $2 == "yes" || $2 == "y" ]; then
			$INTERNET_ACCESS = ""
			shift 2
		elif [ $2 == 0 || $2 == "no" || $2 == "n" ]; then
			$INTERNET_ACCESS = " --unshare-net "
		else; then
			echo "Usage: --internet-access [ {1, yes, y} or {0, no, n} ]"
			exit 1
		fi
		;;
			
	
	--)
		shift
		break
		;;
	
	*)
		break
		;;
	esac
done

if [ $# -eq 0 ]; then
	echo "Usage: sandbox.sh [--mode MODE] [--session-name NAME] -- command [args...]"
	exit 1
fi

USER="$(id -un)"
HOME_REAL="$HOME"
RUNTIME="$XDG_RUNTIME_DIR"
SANDBOX_BASE="$HOME_READ/.sandbox"
EXPORT_DIR="$SANDBOX_BASE/export"

BASE_SYSTEM="
	--ro-bind /usr /usr
	--ro-bind /bin /bin
	--ro-bind /sbin /sbin
	--ro-bind /lib /lib
	--ro-bind /lib64 /lib64
	--ro-bind /etc /etc
	--proc /proc
	--dev /dev
"

# -------------- Modes --------------

case "$MODE" in

normal)
	exec "$@"
	;;

contained)
	SANDBOX_HOME="$SANDBOX_BASE/contained/$SESSION"

	mkdir -p "$SANDBOX_HOME"/.config
	mkdir -p "$SANDBOX_HOME"/.local/share
	mkdir -p "$SANDBOX_HOME"/.cache
	mkdir -p "EXPORT_DIR"

	exec bwrap \
		--unshare-all \
		--new-session \
		$BASE_SYSTEM \
		--bind "$SANDBOX_HOME" /home/$USER \
		--setenv HOME /home/$USER \
		--setenv USER "$USER" \
		--setenv LOGNAME "$USER" \
		--setenv XDG_CONFIG_HOME /home/$USER/.config \
		--setenv XDG_DATA_HOME /home/$USER/.local/share \
		--setenv XDG_CACHE_HOME /home/$USER/.cache \
		--setenv XDG_RUNTIME_DIR "$RUNTIME" \
		$INTERNET_ACCESS \
		--bind "$RUNTIME" "$RUNTIME" \
		--bind "$EXPORT_DIR" /export \
		"$@"
	;;

volatile)
	
	mkdir -p "$EXPORT_DIR"

	exec bwrap \
		--unshare-all \
		--new-session \
		$BASE_SYSTEM \
		--tmpfs /home \
		--dir /home/$USER \
		--setenv HOME /home/$USER \
		--setenv USER "$USER" \
		--setenv LOGNAME "$USER" \
		--setenv XDG_CONFIG_HOME /home/$USER/.config \
		--setenv XDG_DATA_HOME /home/$USER/.local/share \
		--setenv XDG_CACHE_HOME /home/$USER/.cache \
		--setenv XDG_RUNTIME_DIR "$RUNTIME" \
		$INTERNET_ACCESS \
		--bind "$RUNTIME" "$RUNTIME" \
		--bind "$EXPORT_DIR" /export \
		"$@"
	;;

*)
	echo "Unknown mode: '$MODE'"
	exit 1
	;;
esac
