#!/bin/bash
PATH=$PATH:.
PTT_YESNO="y"
if [ "$1" = "-y" ]; then
	PTT_YESNO=
	shift
fi
PTT_ASLF=$1
if [ "$PTT_ASLF" = "" ]; then
	PTT_ASLF="--help";
fi
if [ "$PTT_ASLF" = "-h" ]; then
	PTT_ASLF="--help";
fi
if [ "$PTT_ASLF" = "--help" ]; then
	echo "Transfer Phisical FILE from iSeries and convert it to Output_File.csv"
        echo ""
        echo "Usage: "
	echo "  `basename $0` [-y] [LIBRARY/]FILE [Output_File] [iSeries_Hostname]"
        echo ""
        echo "    when not specified, LIBRARY name will default to \"CWF\","
	echo "    Output_File will be \"FILE.csv\", and iSeries will be \"iseries\""
	echo "    specifing \"-y\" you can save temporary xml file"
        echo ""
        exit 0
fi	
PTT_ASLIB=`echo $PTT_ASLF | cut -d"/" -f1 -s`
PTT_ASFILE=`echo $PTT_ASLF | cut -d"/" -f2`
if [ "$PTT_ASLIB" = "" ]; then
	PTT_ASLIB=CWF
fi
PTT_OUTFILE=$2
if [ "$PTT_OUTFILE" = "" ]; then
	PTT_OUTFILE=$PTT_ASFILE
fi
PTT_ISERIES=$3
if [ "$PTT_ISERIES" = "" ]; then
	PTT_ISERIES=iseries
fi
if [ "x$ASDBGET_PASSWORD" = "x" ]; then
	export ASDBGET_PASSWORD=quser
fi

echo -n "Retrieving file $PTT_ASLIB/$PTT_ASFILE... "
asdbget64 -u quser $PTT_ISERIES $PTT_ASLIB/$PTT_ASFILE -o /tmp/$PTT_OUTFILE.xml \
|| while (true); do echo "error. exiting..."; exit 1; done
echo "done."

echo -n "Generating /tmp/$PTT_OUTFILE.csv... "
cat /tmp/$PTT_OUTFILE.xml | asdb2tab_ptt > /tmp/$PTT_OUTFILE.csv
echo "done."

if [ "$PTT_YESNO" = "" ]; then
	echo -n "Remove /tmp/$PTT_OUTFILE.xml file? [y/N]: "
	read PTT_YESNO
fi
if [ "$PTT_YESNO" = "y" ]; then
	rm /tmp/$PTT_OUTFILE.xml
	echo "/tmp/$PTT_OUTFILE.xml removed. "
fi

