#!/bin/bash

i=0
n=0

not_accept="/"
max_files=1
dirs="/home/ftp/pub/"

files="/home/ftp/pub/liga_all.zip"

if ! [ $# = 0 ]; then
while :
do
  let i=i+1
  eval str=\$$i
  if ! [ `echo $str|cut -b-1` = '-' ] ; then
    case $n in
	0) ftn=$str;;
	1) req=$str;;
	2) out=$str;;
	3) rep=$str;;
    esac
    let n=n+1
  fi
  if [ $i = $# ] ; then break; fi
done
fi

if ! [ $n = 4 ]
then
  echo "Usage: $0 ftnaddress reqfile outfile reportfile"
  exit
fi

if ! [ -f $req ]
then
  echo "$req - unable to read"
  exit
fi

>$rep
>$out

#cp -f $req /tmp/req.zzz.$$

#echo $* >/tmp/$$.FUCK

if ! [ -f $req ] ; then echo "empty list - ignore this message">>$rep; exit ; fi

for i in `cat $req`
do

  i=`echo $i|awk -F\| '{print $1}'`

  lowcase_name=`echo $i|tr A-Z a-z`

  if [ $lowcase_name = "files" ]
  then
    if ! [ -z $files ]
    then
      echo "$files `basename $files`">>$out
      echo "$files (filelist) sent">>$rep
    fi
  else
    count=0
  
    i=`echo $i|sed "s/\.\.\///g"|tr -d "$not_accept"`
  
    j=`find $dirs -iname $i 2>/dev/null`
    if [ -z $j ]
    then
      echo "$i not found">>$rep
    else
      for k in $j
      do
        if [ $count = $max_files ]
        then
          echo "$k - not available">>$rep
        else
          echo "$k `basename $k`">>$out
          echo "$k sent">>$rep
  	let count=count+1
        fi
      done
    fi
  fi
done

#cp -f $out /tmp/out.zzz.$$
#cp -f $rep /tmp/rep.zzz.$$
