#!/bin/bash
# -*- coding: utf-8 mode: sh -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8

function display_help() {
    uecho "$scriptname: convertir des fichiers dans un autre encoding

USAGE
    $scriptname [-f src_enc] [ -t dest_enc] [/path/to/file]

OPTIONS
    -f from
        Encoding source. Si n'est pas spécifié ou vaut 'detect', l'encoding est
        autodétecté.
    -t to
        Encoding destination. Doit être spécifié.
        Cas particulier: si to vaut 'lf' ou 'crlf', from est ignoré, et seuls
        les caractères de fin de lignes sont convertis.
    -N  Ne pas optimiser le calcul de l'encoding. Cette option n'est valide que
        si -f n'est pas spécifié. On assume que tous les noms de fichiers n'ont
        pas le même encoding. L'encoding from est donc recalculé à chaque fois.
    -r  inverser from et to, qui doivent être tous les deux spécifiés."
}

if [ "$#" -eq 1 -a "$1" == --nutools-makelinks ]; then
    # créer les liens
    scriptname="$(basename "$0")"
    for destenc in latin1 utf8 lf crlf cr; do
        ln -s "$scriptname" "${scriptname}2$destenc"
    done
    exit 0
fi

source "$(dirname "$0")/lib/ulib/ulib" || exit 1
urequire DEFAULTS

from=detect
case "${scriptname#fconv2}" in
utf8) to=utf-8;;
latin1) to=iso-8859-1;;
lf) to=lf;;
crlf) to=crlf;;
cr) to=cr;;
*) to=;;
esac
optimize=1
parse_opts "${PRETTYOPTS[@]}" \
    --help '$exit_with display_help' \
    -f: from= \
    -t: to= \
    -N optimize= \
    -r reverse \
    @ args -- "$@" && set -- "${args[@]}" || die "$args"

function dfconv() {
    # $1 = répertoire dont les fichiers doivent être convertis
    local srcdir="$1" files file
    array_lsall files "$srcdir"
    for file in "${files[@]}"; do
	fconv "$file"
    done
}

function ffconv() {
    # $1 = fichier à renommer
    local lfrom="$from" lto="$to"
    local src="$1"

    if [ "$to" == "lf" ]; then
        ebegin "$src" nl2lf "$src"
    elif [ "$to" == "crlf" ]; then
        ebegin "$src" nl2crlf "$src"
    elif [ "$to" == "cr" ]; then
        ebegin "$src" nl2cr "$src"
    else
        if [ "$lfrom" == "detect" ]; then
	    lfrom="$("$scriptdir/lib/pywrapper" uencdetect.py -f "$src")"
	    if [ "$lfrom" == "Unknown" ]; then
	        eerror "$(ppath "$src"): Impossible de déterminer l'encoding"
	        return 1
	    fi
	    if [ -n "$optimize" ]; then
	        from="$(__norm_encoding "$lfrom")"
                [ "$from" != "$to" ] && enote "Conversion $from --> $to"
	    fi
        fi
        if [ -n "$optimize" -a "$from" == "$to" ]; then
            die "Une conversion de $from à $to n'a pas de sens.
Veuillez re-essayer avec -N si nécessaire."
        fi
        
        if [ -n "$reverse" ]; then
            local tmp="$lto"
            lto="$lfrom"
            lfrom="$tmp"
        fi

        local tmp="$src.tmp.$$"
        autoclean "$tmp"
        ebegin "$src"
        iconv -f "$lfrom" -t "$lto" "$src" >"$tmp" &&
        (cat "$tmp" >"$src"; edot) &&
        (rm "$tmp"; edot)
        eend
    fi
}

function fconv() {
    if [ -d "$1" ]; then
        etitle "$(ppath "$1")" dfconv "$1"
    elif [ -f "$1" ]; then
        ffconv "$1"
    else
        eerror "$1: fichier introuvable ou invalide"
    fi
}

[ -n "$to" ] || die "Il faut spécifier l'encoding de destination"
to="$(__norm_encoding "$to")"

if [ -n "$*" ]; then
    if [ "$to" == "lf" -o "$to" == "crlf" -o "$to" == "cr" ]; then
        enote "Conversion [cr]lf --> $to"
    fi
    for src in "$@"; do
        fconv "$src"
    done
elif [ "$to" == "lf" ]; then
    nl2lf
elif [ "$to" == "crlf" ]; then
    nl2crlf
elif [ "$to" == "cr" ]; then
    nl2cr
fi