#!/bin/dash
# Convert a directory package to SFS
# Copyright (C) James Budiono 2017
# License: GNU GPL Version 3 or later
#

### configuration
COMPRESSION=${COMPRESSION:--comp xz}
APPTITLE="dir2sfs"

# $1-msg
info_bg() {
	if [ "$DISPLAY" ]; then
		Xdialog --title "$APPTITLE" --infobox "$1" 0 0 999999999 &
	else
		dialog --title "$APPTITLE" --infobox "$1" 0 0 &
	fi
}

# $1-msg
msg() {
	if [ "$DISPLAY" ]; then
		Xdialog --title "$APPTITLE" --msgbox "$1" 0 0
	else
		dialog --title "$APPTITLE" --msgbox "$1" 0 0
	fi
}

# $1-msg
die() {
	msg "$1"
	exit 1
}

### main
# 1. sanity checks
case "$1" in
	""|-h|--help) die "Usage: ${0##*/} /path/to/dir" ;;
esac

SRC="$1"
TARGET=${SRC%/}.sfs
! [ -e "$SRC" ] && die "$1 does not exist."
! [ -r "$SRC" ] && die "$1 is not readable."
[ -L "$SRC" ] && SRC=$(readlink -f "$1")
[ -e "$TARGET" ] && die "$TARGET already exist."

# 2. show wait dialog
info_bg "Please wait, converting..."
PID=$!

# 3. do the work
chmod 755 "$SRC" # make sure root dir is always correct mode
mksquashfs "$SRC" "$TARGET" $COMPRESSION
kill -0 $PID 2>/dev/null && kill $PID
msg "Done. Created $TARGET."
