# avglen2.sh
# domaci ukol c.1 - skript, ktery vypise prumernou delku jmen souboru v aktualnim
#+adresari, vcetne jmen (pod)adresaru
# verze 2 - vyuziva utility bc pro vypocet floating point numbers
# pozor - wc pocita i newlines => musi se odecist
# skript nezahrnuje soubory . a .. (nemelo by to smysl)
# preferuji spise anglicke nazvy promennych, protoze jsou kratsi a vystiznejsi
# chmod a+rx avglen2.sh
# su; cp avglen2.sh /usr/local/bin
# v aktualnim adresari spustim skript jednoduse takto: avglen2.sh
#+(skript samotny je v adresari /usr/local/bin, ktery je v $PATH)
# z bezpecnostnich duvodu (na mem systemu - setuid muj system nepovoluje) 
#+bezi skript pouze v home; aby bezel i vsude jinde, 
#+je zapotrebi se nejdrive prihlasit jako root (su). Snad to je mozne nejak obejit

#!/bin/bash
touch $PWD/temporary

echo -n "Include hidden files? (y / n): "
read answer

while [[ $answer != "y" && $answer != "n" ]]; do
    echo "You must enter either y or n. Try again."
    echo -n "Include hidden files? (y / n): "
    read answer
done

echo

if [[ $answer == "y" ]]; then
    ls -a > temporary
#     cat temporary
    any=$(( $(wc -w < temporary) - 1 )) # -1, protoze temporary obsahuje temporary

    if (( any > 2 )); then # > 2, protoze . a .. jsou vzdy pritomny
        num_files=$(( $(wc -w < temporary) - 3 )) # tj. minus temporary, . a ..
        echo "Number of files in the current directory: "$num_files

        newlines=$(wc -l < temporary)
        num_chars=$(( $(wc -m < temporary) - newlines - 12 )) #temporary ma 9 znaku 
                                                              # + 3 znaky pro . a ..

#         whole=$((num_chars / num_files))
#         fraction=$(( (100 * (num_chars % num_files)) / num_files )) # precision = 2
#         echo "Average length of file names: "$whole.$fraction

        avg=$( echo "scale=2; $num_chars/$num_files" | bc )
        echo "Average length of file names: $avg"
    else
        echo "There are no files in the current directory"
    fi
elif [[ $answer == "n" ]]; then
    ls > temporary
#     cat temporary
    any=$(( $(wc -w < temporary) - 1 )) # -1, protoze temporary obsahuje temporary

    if (( any > 0 )); then
        num_files=$(( $(wc -w < temporary) - 1 )) # tj. minus temporary
        echo "Number of files in the current directory: "$num_files

        newlines=$(wc -l < temporary)
        num_chars=$(( $(wc -m < temporary) - newlines - 9 )) #temporary ma 9 znaku

#         whole=$((num_chars / num_files))
#         fraction=$(( (100 * (num_chars % num_files)) / num_files )) # precision = 2
#         echo "Average length of file names: "$whole.$fraction

        avg=$( echo "scale=2; $num_chars/$num_files" | bc )
        echo "Average length of file names: $avg"
    else
        echo "There are no files in the current directory"
    fi
fi

rm temporary
echo
exit

