#!/bin/bash

# SCRIPT 3
# Dimiourgiste ena script me onoma tis epilogis sas pou
# 8a dexetai akribws ena orisma.
# 1. Na eleghete to pli8os ton orismaton
# 2. Ne eleghete an to orisma pou exei do8ei antistoixei se
#    arxeio pou uparxei.
# 3. To arxeio 8a prepei na exei akereious ari8mous. Enan se
#    ka8e grammi, xwris kena, kenes grammes i allous xaraktires.
#    Afou ginoun oi parapanw eleghoi, to script 8a prepei na
#    diavazei grammi-grammi ta periexomena tou arxeiou kai na
#    ypoologizei to a8roisma ton ari8mon.
#
# Prosoxi:
# A) Ton elegho gia ta periexomena tou arxeiou (ari8moi) mporeitai
# na ton kanete eite grammi-grammi, eite synolika (me grep) se olo
# to arxeio, diladi na breite an yparxoun grammes pou den pliroun
# ta kritiria mas.
# B) Ta minimata la8ous ektypwnontai stin e3odo la8on
#    (echo "" >&2)
# C) Se priptosi la8ous, prepei na ginetai e3odos me ton katallilo
#    Kodika sfalmatos  (exit 1)
# prints sum of all rows of an integer-only file

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

# an o arithmos ton orismaton ($#) den einai 1 
# tote error kai exit
if ! [ "$#" -eq 1 ]; then
	echo "Usage: $0 file" >&2
	exit 1
fi

# an to arxeio ($1) den yparxei
# tote error kai exit
if ! [ -e "$1" ]; then
	echo "$1: does not exist" >&2
	exit 1
fi

# an to orisma ($1) den einai arxeio
#tote error kai exit
if ! [ -f "$1" ]; then
	echo "$1: not a file" >&2
	exit 1
fi

# tsekaroume me to grep an yparxoun mi-psifia sto
# arxeio ($1)
egrep "[^0-9]" "$1" > /dev/null;

# an nai, error kai exit
if [ "$?" -eq 0 ]; then
	echo "$1: does not include only integers" >&2;
	exit 1
fi

# pros8etoume ka8e seira tou arxeiou ($1) sto $sum
sum=0
while read p; do
	let "sum=sum+p"
done < "$1"

echo $sum
