#!/usr/bin/env bash

# Read in language
source ${BBROOTDIR}/lang/${BBLANG}/loopback.lang

# Directory names
BB_LB_DIR="/tmp/bb-loopback"
BB_IM_COPY_DIR="/tmp/imagecopy"

#
# This file has functions for mounting an image file in a loopback
# device and edit its contents. After editing, a new image file
# is created containing the edited material.
#

# Remove temporary directories
cleanup()
{
	  sudo umount "$BB_LB_DIR"
	  rm -rf "$BB_IM_COPY_DIR"/*
}

# Bad filename?
if [ ! -r "$1" ]; then
	echo " \"$1\" $bb_lb_noread"
	exit 100
fi

# Create necessary directories if possible
if [ ! -e "$BB_LB_DIR" ]; then
	echo "$bb_lb_no_lb_dir"
	if mkdir "$BB_LB_DIR"; then
		echo "$bb_lb_dir_c"
	else
		echo "$bb_lb_dir_cf"
		exit 2
	fi
fi

if [ ! -e "$BB_IM_COPY_DIR" ]; then
	echo "$bb_lb_no_im_dir"
	if mkdir "$BB_IM_COPY_DIR"; then
		echo "$bb_lb_dir_c"
	else
		echo "$bb_lb_dir_cf"
		exit 3
	fi
fi

if [ ! -e "${BBBURNDIR}" ]; then
	echo "$bb_lb_no_temp_dir"
	if mkdir /tmp/burn; then
		echo "$bb_lb_dir_c"
	else
	echo "$bb_lb_dir_cf"
	exit 4
	fi
fi

# Mount the CD image in a loopback device
if [ $(whoami) != 'root' ];then
	echo "$bb_lb_sudo1"
	echo "$bb_lb_sudo2"
	echo "$bb_lb_sudo3"
	echo "$bb_lb_sudo4"
	echo "$bb_lb_sudo5"
	echo "$bb_lb_sudo6"
	if sudo mount -t iso9660 -o loop "$1" "$BB_LB_DIR"; then
		echo "$bb_lb_mount"
	else
		echo "$bb_lb_mount_fail"
		exit 5
	fi
elif mount -t iso9660 -o loop "$1" "$BB_LB_DIR"; then
	echo "$bb_lb_mount"
else
	echo "$bb_lb_mount_fail"
	exit 6
fi	

# Copy contents from the mounted image to another directory and set
# new permissions so its contents can be manipulated.
echo "$bb_lb_cp_cont"
cp -R "$BB_LB_DIR"/* "$BB_IM_COPY_DIR"
chmod -R +w "$BB_IM_COPY_DIR"

# Change to new directory and start a shell session there
cd "$BB_IM_COPY_DIR"
echo "$bb_lb_in_file"
bash

# When user exits shell session, change to temporary file directory and
# create new image file out of what user manipulated (If anything was).
echo "$bb_lb_change1"
echo "$bb_lb_change2"
echo -n "|> "
read answer
if [ "$answer" == "y" ]; then
	# We want to make sure no data is deleted by mistake
	if [ "$(ls -A ${BBBURNDIR})" ]; then
		echo "$bb_lb_change3 \"${BBBURNDIR}\","
		echo "$bb_lb_change4"
		echo -n "$bb_lb_change5"
		echo -n "|> "
		read answer
		if [ "$answer" == "y" ]; then
			cd "${BBBURNDIR}"
			rm -rf "${BBBURNDIR}"/*
			echo "$bb_lb_change6"
			if eval "${BB_ISOCMD} -r -f -v -J -hide-joliet-trans-tbl -o BashBurn.iso \"$BB_IM_COPY_DIR\""; then
				echo "$bb_lb_change7 \"${BBBURNDIR}\""
			fi
		else
			echo "$bb_lb_change8"
			cleanup
		fi
	fi 
else
	echo "$bb_lb_change9"
fi

# Finally clean up our mess
cleanup



syntax highlighted by Code2HTML, v. 0.9.1