#!/bin/bash

# SCRIPT 2
#
# Dimiourgiste senario (script) kelyfous. To senario 8a dexete 
# aperiorista orismata pou einai onomata katalogon.
#
# To script 8a prepei:
# 1. Na eleghei to plithos ton orismaton
# 2. Na eleghei an ta orismata pou do8ikan einai katalogoi/fakeloi
#    An brei kapoio pou den einai katalogos, tote emfanizei minima
#    la8ous kai kanei e3odo.
# 3. Gia ka8e katalogo na briskei kai na typwnei to pli8os ton
#    arxeion pou anikoun se ka8e group ston sygkekrimeno katalogo
# 4. Ta apotelesmata 8a prepei na typwnontai me sygkekrimeni
#    morfopoiisi opws fainetai sto paradeigma.
# 5. Ta apotelesmata na emfanizontai ta3inomimena symfona me to
#    pli8os ton arxeion.

# Profanos, to senario sas 8a prepei na emfanizei ta minimata la8on
# echo "error" >&2
# stin e3odo la8on. Episis, se periptosi sfalmatos, 8a prepei na ginetai
# e3odos me ton katallilo kodiko (exit 1)

# Paradeigma ektelesis:
# 
#   $./script /etc /bin
#   /etc:
#       180 root
#         2 shadow
#         1 nslcd
#         1 daemon
#   
#   /bin:
#       140 root


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

# 1
# an o ari8mos ton orismaton einai 0, error kai exit
if [ "$#" -eq 0 ]; then
	echo "Usage: $0 dir dir2 dir3 " >&2
	exit 1
fi



# 2
# gia ka8e orisma, an to orisma den einai fakelos
# tote error kai exit
for arg in "$@"
do
	if ! [ -d "$arg" ]; then
		echo "$arg: not a directory" >&2
		exit 1
	fi
done 


# 3
# gia ka8e orisma (fakelo)
for arg in "$@"
do
	echo "$arg:"
	ls -l $arg/* | tr -s " " | cut -d" " -f4 | uniq -c | sort -r -n
	# ls -l $arg/*    deixnoume ta arxeia tou
	# tr -s " "       simpiezoume ta kena
	# cut -d" " -f4   pernoume to 4o pedio (ta pedia xorizontai me kena)
	# uniq -c         emfanizoume tin ka8e diaforetiki seira mia fora mazi me count
	# sort -r -n      antistrofi ari8mitiki taxinomisi
done 
