lxc-snapshot 1.31 KB
#!/bin/sh

function lxc-snapshot()
{
	local BTRFS=/sbin/btrfs
	local CHMOD=/bin/chmod
	local CHOWN=/bin/chown
	local CUT=/usr/bin/cut
	local ECHO=/bin/echo
	local GREP=/bin/grep
	local ID=/usr/bin/id
	local LXC_USERNSEXEC=/usr/bin/lxc-usernsexec
	local MKDIR=/bin/mkdir
	local SED=/bin/sed
	local TEST=/usr/bin/test

	local SOURCE=$1
	local TARGET=$2
	local IP=$3

	local SUBUIDS=$(${GREP} ${USER} /etc/subuid)
	local SUBGIDS=$(${GREP} ${USER} /etc/subgid)
	local SUID_START=$(${ECHO} "${SUBUIDS}" | ${CUT} -d: -f2)
	local SGID_START=$(${ECHO} "${SUBGIDS}" | ${CUT} -d: -f2)

	local HUID=$(${ID} -u)
	local HGID=$(${ID} -g)

	${MKDIR} "${HOME}/.local/share/lxc/${TARGET}"
	${CHMOD} 770 "${HOME}/.local/share/lxc/${TARGET}"
	${SED} 's/'${SOURCE}'/'${TARGET}'/;/lxc.network.ipv4 *=/s/= *.*/= '${IP//\//\\/}'/' \
		"${HOME}/.local/share/lxc/${SOURCE}/config" >"${HOME}/.local/share/lxc/${TARGET}/config"
	${LXC_USERNSEXEC} -m 'u:0:'${SUID_START}':1' -m 'g:0:'${SGID_START}':1' \
		-m 'u:'${HUID}':'${HUID}':1' -m 'g:'${HGID}':'${HGID}':1' -- \
		${CHOWN} 0 "${HOME}/.local/share/lxc/${TARGET}"
	${LXC_USERNSEXEC} -m 'u:0:'${SUBUIDS#*:} -m 'g:0:'${SUBGIDS#*:} -- \
		${BTRFS} subvolume snapshot \
		"${HOME}/.local/share/lxc/${SOURCE}/rootfs" \
		"${HOME}/.local/share/lxc/${TARGET}/rootfs"
}

export -f lxc-snapshot

# vim: set ft=sh ts=4 sw=4: