#!/bin/sh
#
# get_text
#
# Usage:   /opt/ac/get_text
#
# This script will find ALL ascii/script/command files under current
# directory.  Then, it will cat those files into : /opt/ac/texts.txt
#
# By:  Angel Corbera, TSID1, Refinery Isla, Curacao
#
 rm /opt/ac/texts.txt /opt/ac/tmp1 /opt/ac/tmp2 > /dev/null 2>&1
DIR=`pwd`
ME=`uname -n`
TODAY=`date`
X=new
#
if [ -f /opt/ac/text.lst ]
then
   echo "Previous text.lst file found!. Do you want to use it? (y/n)"
   read answer
   if [ $answer = "y" ]
   then
      X=prev
   else
      rm /opt/ac/text.lst
   fi
fi
#
if [ $X != "prev" ]
then
  echo "Finding files under directory ($DIR) ... \c"
  find . -depth -print > /opt/ac/tmp1
  N1=`wc -l /opt/ac/tmp1 | awk '{print $1}'`
  echo "($N1 files ) Done!"
  touch /opt/ac/texts.txt /opt/ac/text.lst /opt/ac/tmp2

  echo "Identifying  text/script/command  files ... \c"
  for x in `cat /opt/ac/tmp1`
  do
     file $x | awk '$0~/text/ || $0~/script/ || $0~/commands/ {print substr ($1,1,length($1)-1)}' >> /opt/ac/text.lst
  done
  N2=`wc -l /opt/ac/text.lst | awk '{print $1}'`
  echo ".... ($N2 files) Done!"
fi
#
echo "Getting files size ... \c"
for x in `cat /opt/ac/text.lst`
do
  ls -l $x >> /opt/ac/tmp2 
done
echo "Done!"

cat /opt/ac/tmp2 | awk '
NF == 9 && /^-/ {
        sum += $5
        ++filenum
}
END {
	printf("\tTotal: %d bytes  (%d files)\n", sum, filenum)
}'

echo "\nDo you really want to create the output file, with that size (y/n)?"
read answer
if [ $answer = "n" ]
then
   echo "You might edit /opt/ac/text.lst, delete a few files, and run script again"
   echo "Use size list on /opt/ac/tmp2 as reference"
   echo "Exiting!"
   exit 1
fi

echo "Station: $ME \tDate: $TODAY\n" >> /opt/ac/texts.txt
echo "ASCII/Script/Command Files under directory: $DIR \n" >> /opt/ac/texts.txt
awk '{printf "%10s %9s %0s %0s %0s %-0s\n",$1,$5,$6,$7,$8,$9}' /opt/ac/tmp2 >> /opt/ac/texts.txt

for x in `cat /opt/ac/text.lst`
do
 echo "Adding $x   ...."
 echo "\n" >> /opt/ac/texts.txt
 echo "========== $x ==========" >> /opt/ac/texts.txt
 echo "\n" >> /opt/ac/texts.txt
 cat $x >> /opt/ac/texts.txt
done

echo "\tDone! \tDone! \tDone!"
echo "Do not forget to rename /opt/ac/texts.txt !"
cd /opt/ac
