#!/usr/bin/env bash

mkconf() {
	for i in "${includes[@]}"; do
		echo "lxc.include = $lxf_conf_dir/$i.conf"
	done

	echo "lxc.rootfs.path = $lxf_cont_dir/$cont_name/rootfs"
	echo "lxc.uts.name = $cont_name"
}

mount_cont() {
	ov-mount -n "$cont_name" "$rootfs" "$cont_dir/rootfs"
}

lxf_conf_dir='/etc/lxf/conf'
lxf_cont_dir='/var/lib/lxf/cont'
lxf_rootfs_dir='/var/lib/lxf/fs'

[[ -f '/etc/lxf.conf' ]] && source '/etc/lxf.conf'

while (( $# )); do
	case $1 in
		(-i) includes+=( "$2" ); shift;;
		(-r) rootfs="$2"; shift;;

		(--cont-dir) lxf_cont_dir=$2; shift;;
		(--conf-dir) lxf_conf_dir=$2; shift;;

		(--) shift; break;;
		(-*) echo "Unknown key: $1" >&2: exit 1;;
		(*) break;;
	esac

	shift
done


action=$1; shift; [[ $action ]] || exit 1
cont_name=$1; shift; [[ $cont_name ]] || exit 1

cont_dir="$lxf_cont_dir/$cont_name"

case $action in
	(create|new)
		[[ "$rootfs" ]] || exit 1
		rootfs="$lxf_rootfs_dir/$rootfs"

		[[ -d "$cont_dir" ]] && {
			printf 'Container already exists: %s\n' "$cont_dir" >&2
			exit 1
		}

		mkdir -p "$cont_dir" || exit $?

		mkconf > "$cont_dir/config"
		mount_cont
	;;

	(mount)
		mountpoint -q "$cont_dir/rootfs" && {
			printf 'Container already mounted: %s\n' "$cont_dir/rootfs" >&2
			exit 1
		}

		mount_cont
	;;

	(umount) umount "$cont_dir/rootfs";;
esac