#!/usr/bin/perl
# Script for eliminating none-ASCII characters and spaces from file names
$VERSION = '(C) eko@lanet.lv 2017/09/01 09:00';
# Author: Kārlis Kalviškis <eko@lanet.lv>
# License: GPLv3

# For translation
use Locale::gettext;
use POSIX; 
setlocale(LC_MESSAGES, "");
my $tulkojums =   Locale::gettext->domain_raw('karlo-scripts');

print "\n" . $tulkojums->get('Perl script for eliminating none-ASCII characters and spaces from file names') . ".\n   $VERSION\n";

# Show detail report
$drukaat = 1;
# Rename directories
$ari_dir = 1;
# Do recursively
$visas_dir = 1;

# File counters
$paarsaukts = 0;
$nepaarsaukts = 0;

# Commandline parameters (if any))
foreach (@ARGV){
	if ($_ eq '-nR') {
		$visas_dir = 0 ;
	}
	elsif ($_ eq '-nd') {
		$ari_dir = 0 ;
	}
	elsif ($_ eq '-2') {
		$kaaizrunaa = 1 ;
	}
	elsif ($_ eq '-m') {
		$drukaat = 0 ;
	}
	elsif ($_ eq '-h' || $_ eq '-help' || $_ eq '--help'){
		&paskaidro;
	}
	else {
		push (@dir_saraksts, $_);
	}
}

#### Replacement tabels #################################################

# Strings to be searched:
@meklee = (' ', '%20');
# The replacement strings:
@aizstaaj = ('_', '_');
if (!$kaaizrunaa){
	@meklee =   (@meklee, '_-_', '__');
	@aizstaaj = (@aizstaaj, '-', '_');
}
# Latvian
@meklee =   (@meklee,   'ā', 'č', 'ē', 'ģ', 'ī', 'ķ', 'ļ', 'ņ', 'ō', 'ŗ', 'š', 'ū', 'ž', 'Ā', 'Č', 'Ē', 'Ģ', 'Ī', 'Ķ', 'Ļ', 'Ņ', 'Ō', 'Ŗ', 'Š', 'Ū', 'Ž');
if ($kaaizrunaa){
	@aizstaaj = (@aizstaaj, 'aa', 'ch', 'ee', 'gj', 'ii', 'kj', 'lj', 'nj', 'oo', 'rj', 'sh', 'uu', 'zh', 'Aa', 'Ch', 'Ee', 'Gj', 'Ii', 'Kj', 'Lj', 'Nj', 'Oo', 'Rj', 'Sh', 'Uu', 'Zh');
}
else{
	@aizstaaj = (@aizstaaj, 'a', 'c', 'e', 'g', 'i', 'k', 'l', 'n', 'o', 'r', 's', 'u', 'z', 'A', 'C', 'E', 'G', 'I', 'K', 'L', 'N', 'O', 'R', 'S', 'U', 'Z');
}
# German
@meklee =   (@meklee,   'Ä', 'Ö', 'Ü', 'ä', 'ö', 'ü', 'ß');
if ($kaaizrunaa){
	@aizstaaj = (@aizstaaj, 'AE', 'OE',  'UE', 'ae', 'oe', 'ue', 'ss');
}
else{
	@aizstaaj = (@aizstaaj, 'A', 'E',  'U', 'a', 'e', 'u', 's');
}
#Scandinavian
@meklee =   (@meklee,   'Å', 'å', 'É', 'é', 'Æ', 'æ', 'Œ', 'œ', 'Ø', 'ø', 'Ŋ', 'ŋ', 'Đ', 'đ', 'Ð', 'ð', 'Þ', 'þ');
if ($kaaizrunaa){
	@aizstaaj = (@aizstaaj, 'AU', 'au', 'E', 'e', 'AE', 'ae', 'OE', 'oe', 'EJ', 'ej', 'N', 'n', 'D', 'd', 'D', 'd', 'TH', 'th');
}
else{
	@aizstaaj = (@aizstaaj,'A', 'a', 'E', 'e', 'E', 'e', 'O', 'o', 'O', 'O', 'N', 'n', 'D', 'd', 'D', 'd', 'T', 't'); 
}
# Cyrillic
@meklee =   (@meklee,  'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ё', 'Ю', 'Я', 'а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ё', 'ю', 'я');
if ($kaaizrunaa){
	@aizstaaj = (@aizstaaj,'A', 'B', 'V', 'G', 'D', 'E', 'Zh', 'Z', 'I', 'Ij', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'F', 'H', 'C', 'Ch', 'Sh', 'Sch', 'I', 'Y', 'I', 'E', 'Jo', 'Ju', 'Ja', 'a', 'b', 'v', 'g', 'd', 'e', 'zh', 'z', 'i', 'ij', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'sch', 'i', 'y', 'i', 'e', 'jo', 'ju', 'ja');
}
else{
	@aizstaaj = (@aizstaaj,'A', 'B', 'V', 'G', 'D', 'E', 'Z', 'Z', 'I', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'F', 'H', 'C', 'C', 'S', 'S', 'I', 'Y', 'I', 'E', 'J', 'J', 'J', 'a', 'b', 'v', 'g', 'd', 'e', 'z', 'z', 'i', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'c', 's', 's', 'i', 'y', 'i', 'e', 'j', 'j', 'j');
}

#######################################################################


# If directory name has been specified
if (@dir_saraksts){
	foreach $direktorija (@dir_saraksts){
		$direktorija =~ s/^'|"//;
		$direktorija =~ s/'|"$//;
		$direktorija .= "/";
		print $tulkojums->get('Processing') . " $direktorija\n" if $drukaat;
		&sameklee_dir($direktorija);
	}
}

# Interactive mode
else {
	print "\n" . $tulkojums->get('Base directory') . ": ";
	chomp($direktorija = <STDIN>);
	$direktorija =~ s/^'|"//;
	$direktorija =~ s/'|"$//;
	$direktorija .= "/";
	print "\n" . $tulkojums->get('Starting') . " ...\n";
	&sameklee_dir($direktorija);
}
print "\n\n"  if $drukaat;
print $tulkojums->get('The processed files') .  ($ari_dir?$tulkojums->get(' and '):'') .  ($ari_dir?$tulkojums->get('directories'):'') . ": $paarsaukts \n";
print $tulkojums->get('The unprocessed files') . ($ari_dir?$tulkojums->get(' and '):'') . ($ari_dir?$tulkojums->get('directories'):'') . ": $nepaarsaukts \n";
print "\n\n"  if $drukaat;
exit;


########################################################################


# Recursively search files.
#   $direktorija – directory name.
sub sameklee_dir {
	my($direktorija) = @_;
	my(@failu_saraksts, $tf1, $tf2);
	if (!opendir(DIREKTORIJA_NR, $direktorija)) {
		print $tulkojums->get('Access denied') . ": $direktorija\n" if $drukaat;
		return;
	}
	@failu_saraksts = readdir(DIREKTORIJA_NR);
	close(DIREKTORIJA_NR);
	my $fails;
	foreach $fails (@failu_saraksts) {

		# Only normal files are processed
		if (-f $direktorija . $fails){
			&paarsauc ($direktorija, $fails);
		}

		# IS it a directory?
		elsif (-d $direktorija . $fails && $visas_dir){

			# Dont read directories with a dot at the beginning of the name (also ./ and ../)
			if (!($fails =~ /^\./)) {
				my $jauna_dir = $direktorija . $fails;
				if ($ari_dir) {
					print "\t\t" . $tulkojums->get('Directory') . ": $fails\n" if $drukaat;
					$jauna_dir = &paarsauc ($direktorija, $fails);
				}
				&sameklee_dir($jauna_dir . "/");
				print "\t" . "-"x38 . "\n\t" . $tulkojums->get('Done with') . " $jauna_dir\n" if $drukaat;
			}
		}
	}
}

# Rename the file or directory
sub paarsauc {
	my $direktorija = shift;
	my $tf1 = shift;
	my $tf2 = $tf1;
	for ($ni = 0; $ni < @meklee; $ni++) {
		$tf2 =~ s/$meklee[$ni]/$aizstaaj[$ni]/g;
	}
	if ($tf1 ne $tf2) {
		$tf1 = $direktorija . $tf1;
		$tf2 = &vai_ir($direktorija, $tf2);
		if (!(rename $tf1, $tf2)){
			print $tulkojums->get('Access denied') . ": $tf1\n" if $drukaat;
			$nepaarsaukts++;
			return $tf1;
		}
		else {
			print "\t\t" . $tulkojums->get('Renamed') . ": $tf1\n" if $drukaat;
			$paarsaukts++;
			return $tf2;
		}
	}
	else {
		return $direktorija . $tf1;
	}
}

# Creates non-exiting file name
sub vai_ir {
	my ($celjsh, $faila_vards)= @_;
	my ($fails, $pap, $fails_tmp);
	if ($faila_vards =~ /^(.+)(\..+)$/){
		$fails = $1;
		$pap = $2;
	}
	else {
		$fails = $faila_vards;
	}
	my $pilns_celjsh = "$celjsh$fails$pap";
	my $ni = 0;
	while (-e $pilns_celjsh) {
		$fails_tmp = $fails . '_' . ++$ni . $pap;
		$pilns_celjsh = "$celjsh$fails_tmp";
	}
	return $pilns_celjsh;
}

# Help message
sub paskaidro {
	print "\n" . '-' x 60  . "\n" .
		"$0  [" . $tulkojums->get('Options') . '] [' . $tulkojums->get('Directory') . '1] [' . $tulkojums->get('Directory') . "2] [...]\n" .
		' ' x 6 . $tulkojums->get('Options') . ":\n" .
		' ' x 9 . '-2	' . $tulkojums->get('More than one character may be used as replacement') . ";\n" .
		' ' x 9 . '-h	' . $tulkojums->get('This help message') . ";\n" .
		' ' x 9 . '-nd	' . $tulkojums->get("Don't rename directories") . ";\n" .
		' ' x 9 . '-m	' . $tulkojums->get('Only the count of processed files is displayed') . ";\n" .
		' ' x 9 . '-nR	' . $tulkojums->get("Don't process the directories recursively") . ";\n" .
		'-' x 60 . "\n";
	exit;
}
