#!/bin/bash
#########################################################
# 							#
# This is BashStyle-NG  				#
#							#
# Licensed under GNU GENERAL PUBLIC LICENSE v3    	#
#							#
# Copyright Christopher Bratusek			#
#							#
#########################################################

. gettext.sh
export TEXTDOMAIN="bashstyle-rc"

fill_zeros () {
	current_len=${#1}
	diff_string=""

	if [[ ${current_len} -ne ${count_len} ]]; then
		diff_len=$((count_len-current_len))
		while test ${diff_len} -ne 0; do
			diff_string="${diff_string}0"
			diff_len=$((diff_len-1))
		done
		echo ${diff_string}
	fi
}

rename_files () {
	mkdir "${directory}/tmp"

	count_max=$(($(find "${directory}" -maxdepth 1 -type f | wc -l)))
	count_len=${#count_max}
	count_now=1

	[[ "${MV_OPT}" == "-v" ]] && \
		echo -e "$(eval_gettext "\n\n >> renaming files using temporary directory \"${directory}/tmp\" \n\n")"

	OLD_IFS="${IFS}"
	export IFS=$'\n'

	files=($(find "${directory}" -maxdepth 1 -type f))

	for image in "${files[@]}"; do
		suffix=$(fill_zeros ${count_now})${count_now}.${image##*.}
		mv ${MV_OPT} "${image}" "${directory}/tmp/${prefix}-${suffix}"
		count_now=$((count_now+1))
	done

	[[ "${MV_OPT}" == "-v" ]] && \
		echo -e "$(eval_gettext "\n\n >> moving files into destination directory \"${directory}\" \n\n")"

	mv ${MV_OPT} "${directory}/tmp/"* "${directory}/"
	rmdir "${directory}/tmp"

	export IFS="${OLD_IFS}"
}

_help () {
	bashstyle-help -a "Christopher Roy Bratusek" -e "nano@jpberlin.de" \
		-h "https://www.nanolx.org/" -l "GNU GPL v3" -n "batchrename" \
		-s "$(eval_gettext "batch rename files in NNN-NAME.SUFFIX scheme")"\
		-v "${BSNG_VERSION}" -y "${BSNG_YEAR}"\
		-o "$(eval_gettext "v:|verbose output")"\
		-o "$(eval_gettext "directory:/home/test/mypictures|directory containing files")"\
		-o "$(eval_gettext "prefix:MyPictures2016|NAME part of the NNN-NAME.SUFFIX scheme")"
}

case ${1} in
	v | verbose )
		export MV_OPT="-v"
		shift
	;;
esac

if [[ $# -ge 2 ]]; then
	directory="${1}"

	if [[ ! -d "${directory}" ]]; then
		echo "$(eval_gettext "directory \"${directory}\" does not exist!")"
		exit 1
	elif [[ ! -w "${directory}" ]]; then
		echo "$(eval_gettext "directory \"${directory}\" is not writeable!")"
		exit 1
	fi

	prefix="${2}"
	rename_files
else
	_help
fi

