#!/bin/bash
# Arregla el nom dels fitxers treient els caracters en blanc i potser els accents
PrOgRaM="`basename "$0"`"
function Error_Avortant(){ echo -e "\nERROR a ${PrOgRaM}: ${1}.\nAvortant...\n" ;  exit 1 ; }
function HELP(){ echo -e "\nUs: ${PrOgRaM} [-a | --treu-accents] <nom_de_fitxer>\n"; exit 1 ; }
TreuAccents=false
#
[ $# -eq 0 ] && HELP
for FiTxEr ; do
  case "$FiTxEr" in
    -a | --treu-accents) TreuAccents=true ;;
    -*) HELP ;;
     *) ;; # [ -w "$FiTxEr" ] || Error_Avortant "fitxer '${FiTxEr}' no trobat o no modificable" ;;
  esac
done
### Calcul del nom nou separat en nom i extensió
if [ -d "$FiTxEr" ] ; then  FiTxEr="${FiTxEr%%/}" ; NomNou="$FiTxEr" ; ext=""
else NomNou="${FiTxEr%.*}" ; ext="${FiTxEr:${#NomNou}}" ; ext="${ext,,*}" ; fi 
### Treiem accents si cal
$TreuAccents && NomNou="$( echo "$NomNou" | iconv -f utf8 -t ascii//TRANSLIT | tr -d '^~\042\047\140' )"
### Treiem espais en blanc i caracters indesitjats
NomNou="$( echo "$NomNou" | sed -e 's/&\+/and/' | 
                            tr -cs "0-9A-Za-z-\./_" _ | 
                            sed -e '{s/\.\+/\./g; s/[-_]*-[-_]*/-/g; s![-_]*/[-_]*!/!g; s/^[-_]*//; s/[-_]*$//;}'
         )${ext}"
#
[ "$FiTxEr" == "$NomNou" ] || mv -v  "$FiTxEr" "$NomNou"
#
