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

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

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"
	reverse=${1}

	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))

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

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

	[[ "${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 NAME-NNN.SUFFIX scheme")"\
		-v "${BSNG_VERSION}" -y "${BSNG_YEAR}"\
		-o "$(eval_gettext "v:|verbose output")"\
		-o "$(eval_gettext "r:|reverse filename to NNN-NAME.SUFFIX scheme")"\
		-o "$(eval_gettext "directory:/home/test/mypictures|directory containing files")"\
		-o "$(eval_gettext "prefix:MyPictures2016|NAME part of the NNN-NAME.SUFFIX scheme")"
}

if [[ $# -gt 2 ]]; then
	while [[ $# -gt 2 ]]; do
		case ${1} in
			v | verbose )
				MV_OPT="-v"
				shift
			;;

			r | reverse )
				REVERSE_NAME=1
				shift
			;;
		esac
	done
fi

if [[ $# -eq 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 ${REVERSE_NAME}
else
	_help
fi

