#!@TERMUX_PREFIX@/bin/bash
##
## Termux script for backing up $PREFIX (package installation dir).
## For restore script, see "termux-restore".
##
## Why it doesn't implement support for backing up $HOME: that's all
## about implementation of termux-restore script:
##
##  * termux-restore can't selectively restore files due to tar option
##     --recursive-unlink, that will erase file tree before extracting.
##
##  * termux-restore has to maintain support of piped input. Therefore
##    we can't allow optional backup of home by termux-backup. Here is
##    why: with piped input it is not possible to check contents of
##    backup file (you can't seek piped content twice). We must be
##    sure that all directories selected for restore are present
##    inside archive and this is possible only with hardcoded
##    configuration (e.g. backup only $PREFIX). Otherwise, for example,
##    restore procedure may fail or even worse, erase all directories
##    (potentially user data) that are not present in backup.
##
## Considering the mentioned 2 major issues, should be obvious that
## we have literally 2 choices: either backup only $PREFIX or backup
## both $HOME and $PREFIX unconditionally, to ensure consistency of
## data passed to termux-restore.
##
## However the current choice is to stick to backing up only $PREFIX,
## to leave responsibility of managing files in $HOME to user (as said
## above, termux-restore script ERASES DATA before restore).
##

set -e -u

export PREFIX=@TERMUX_PREFIX@

msg() {
	echo "$*" >&2
}

show_usage() {
	msg
	msg "Usage: termux-backup [output file]"
	msg
	msg "Script for backing up Termux installation directory, \$PREFIX."
	msg "It WILL NOT backup your home directory."
	msg
	msg "Backup is performed as TAR archive. Compression is determined"
	msg "by output file extension. If file name is '-', then tarball is"
	msg "written to stdout and is uncompressed."
	msg
}

if [ $# -lt 1 ]; then
	msg
	msg "[!] Output file path is not specified."
	show_usage
	exit 1
fi

if [ $# -gt 1 ]; then
	shift 1
	msg
	msg "[!] Got extra arguments: $*"
	show_usage
	exit 1
fi

if [ ! -d "$PREFIX" ]; then
	msg "[!] $PREFIX: directory does not exist."
	exit 1
fi

case "$1" in
	-\?|-h|--help|--usage) show_usage; exit 0;;
	*) BACKUP_FILE_PATH=$1;;
esac

if [ "$BACKUP_FILE_PATH" != "-" ]; then
	CAN_AUTOCOMPRESS=yes
	if [ -e "$BACKUP_FILE_PATH" ]; then
		msg
		msg "[!] Refusing to overwrite already existing file '$BACKUP_FILE_PATH'."
		msg
		exit 1
	fi
else
	CAN_AUTOCOMPRESS=
fi

msg "Backing up installed packages..."
tar --warning=no-file-ignored -f "$BACKUP_FILE_PATH" \
	-c ${CAN_AUTOCOMPRESS+--auto-compress} \
	-C "@TERMUX_BASE_DIR@" ./usr
