Commits

Jack Frost  committed 043b132

renamer

  • Participants
  • Parent commits 8234801

Comments (0)

Files changed (1)

+#!/usr/bin/env bash
+
+# config
+[[ -e "$HOME/.config/renamer.rc" ]] && { source "$HOME/.config/renamer.rc"; }
+
+cfg_libfbt_path="${cfg_libfbt_path:-/usr/lib/libfbt}"
+cfg_hash_type="${cfg_hash_type:-md5}"
+
+[[ -e "$cfg_libfbt_path" ]] || {
+	echo "This script depends on libfbt: https://github.com/fbt/libfbt"
+	exit 1
+}
+
+source "${cfg_libfbt_path}/libfbt.sh"
+
+# functions
+
+renamer.usage() {
+	lf.msg "Usage: $me [-r]\n"
+}
+
+renamer.args() {
+	while [[ "$1" ]]; do
+		case "$1" in
+			-r|--recursive) flag_recursive='1';;
+			-H|--hash-type) cfg_hash_type="$2"; shift;;
+
+			-h|--help) renamer.usage; exit 0;;
+		esac
+		
+		shift
+	done
+}
+
+renamer.get_files() {
+	local find_args
+
+	[[ "$flag_recursive" ]] || { find_args+='-maxdepth 1'; }
+
+	find . -mindepth 1 ${find_args} -type f
+}
+
+rename.get_file_type() { file -ib "$1"; }
+
+rename.get_file_extention() {
+	case "$1" in
+		*) echo "${1##*/}";;
+	esac
+}
+
+rename.get_file_hash() {
+	case "$cfg_hash_type" in
+		sha1) sha1sum "$1" | cut -d ' ' -f1;;
+		md5) md5sum "$1" | cut -d ' ' -f1;;
+		*)
+			lf.err "No such hash method"
+			exit 1
+		;;
+	esac
+}
+
+renamer.main() {
+	local files
+
+	renamer.args "$(lf.getopt "$@")"
+
+	renamer.get_files | while read line; do
+		file_path="$line"
+		file_type="$(rename.get_file_type "$file_path" | cut -d';' -f1)"
+		file_hash="$(rename.get_file_hash "$file_path")"
+		file_extension="$(rename.get_file_extention "$file_type")"
+		file_new_path="${file_path%%/*}/${file_hash}.${file_extension}"
+
+		[[ "$file_path" == "$file_new_path" ]] || {
+			[[ -e "$file_new_path" ]] && {
+				lf.msg "$file_path == ${file_new_path}\n"
+				[[ -d 'doubles' ]] || {
+					mkdir -p 'doubles' || {
+						lf.msg "Warning! A directory for storing doubles does not exitist and cannot be created! Not removing $file_path"
+					}
+				}
+				mv "$file_path" doubles/
+			} || {
+				lf.msg "$file_path -> ${file_new_path}\n"
+				mv "$file_path" "$file_new_path" 
+			}
+		}
+	done
+}
+
+renamer.main "$@"