#! /bin/sh -
# Depends on GNU cp, log.err

############################### completion start ###############################
options='--no-chattr --no-sudo'
if [ -n "${COMP_LINE}" ] ; then
 if [ "${2#-}" = "${2}" ] ; then
  find "$(dirname -- "${2}")" -mindepth 1 -maxdepth 1 -path "$(dirname -- "${2}")/$(basename -- "${2}")*"
 else
  for option in $options ; do
   case "${option}" in
    "${2}"*) printf '%s\n' "${option}" ;;
   esac
  done
 fi
 exit
fi
################################ completion end ################################

############################ argument parsing start ############################
no_chattr=0
no_sudo=0
while : ; do
	case "${1}" in
		--no-chattr|-c) no_chattr=1 ;;
		--no-sudo|-s) no_sudo=1 ;;
		-*) log.err "Invalid option argument: '${1}'" ; exit 1 ;;
		*) break ;;
	esac
	shift
done

if [ "${#}" -eq "1" ] && [ -n "${1}" ]; then
	backupdir="${HOME}/backups"
	srcfile="${1}"
elif [ "${#}" -eq "2" ] && [ -n "${1}" ] && [ -n "${2}" ] ; then
	backupdir="${1}"
	srcfile="${2}"
else
	log.err "Usage: backup_dir [--no-chattr] [--no-sudo] [BACKUP_DIR] FILE"
	exit 1
fi
############################# argument parsing end #############################

if [ "${no_sudo}" = "1" ] ; then
	sudo_cmd=""
else
	sudo_cmd="sudo --"
fi

backupname="$(basename -- "$srcfile")"

[ -f "${srcfile}" ] || { log.err "Regular File '${srcfile}' does not exist" ; exit 2 ; }
[ -d "${backupdir}" ] || mkdir -p -- "${backupdir}" || { log.err "Backup Directory '${backupdir}' couldn't be created" ; exit 3 ; }

if [ -e "${backupdir}/${backupname}" ] && [ "${no_chattr}" = "0" ] ; then
	$sudo_cmd chattr -i "${backupdir}/${backupname}" || { log.err "Can't chattr -i '${backupdir}/${backupname}'" ; exit 4 ; }
fi
cp --backup=t "${srcfile}" "${backupdir}/${backupname}" || { log.err "Can't cp --backup=t '${srcfile}' '${backupdir}/${backupname}'" ; exit 5 ; }

if [ "${no_chattr}" = "0" ] ; then
	$sudo_cmd find "${backupdir}" -mindepth 1 -exec chattr +i {} + || { log.err "Can't chattr +i some files" ; exit 6 ; }
fi
