#!/bin/sh
#
#######################################################################
#
# extract_install_list <mode> <MEDIADEV> <audit>
#
#   This script uses the TEKXP_FILES.LIST file that contains a list of
#   files that have been selected for extraction (and installation) from
#   the supplied tar file or media file. The mode says whether it is
#   a tar file, cd-rom, or something else.
#
#######################################################################

Usage="Usage: $0 [mode] [media] [file list] [dest] [audit]"

ScriptTag=EXTRACT_FILES

if [ $# -lt 5 ]
then
    echo $Usage; exit 0
fi

PWD=`pwd`

MEDIADEV=$2
FILELIST=$3
DESTDIR=$4
INSTALLDIR=$5
TEKXPHOST=$6
TEKXPUSER=$7
AUDITLOG=$8

if [ "$MEDIADEV" = defdev ]
then
    MEDIADEV=""
fi

Rewind="------------ Rewinding Device $MEDIADEV -----------" 

if [ "$AUDITLOG" ]
then
    PREVRUN=`grep $ScriptTag $AUDITLOG`

    if [ "$PREVRUN" ]
    then
    	exit 1
    fi
else
    echo "Audit empty"
fi

if [ $1 = "tar" ]
then
    if [ -z "$DESTDIR" ]
    then
    	echo "$0: a destination directory must be supplied"
    	exit 0
    fi
    cd $DESTDIR

    $INSTALLDIR/exec_media_cmd $INSTALLDIR tar "$FILELIST" "$MEDIADEV" "$TEKXPHOST" "$TEKXPUSER" "$AUDITLOG"
 
    if [ $? -ne 0 ]
    then
	exit 1
    fi

    $INSTALLDIR/exec_media_cmd $INSTALLDIR rewind "" "$MEDIADEV" "$TEKXPHOST" "$TEKXPUSER" "$AUDITLOG"

    if [ $? -ne 0 ]
    then
	exit 1
    fi

    cd $PWD
fi

if [ $1 = "tcio" ]
then
    if [ "$TEKXPHOST" ]
    then 
	echo "Extracting a tcio HP tape from a remote host is not supported"
        echo "at this time. A local drive must be used."
	echo ""
	exit 1
    fi

    if [ -z "$DESTDIR" ]
    then
    	echo "$0: a destination directory must be supplied" | tee -a $AUDITLOG
    	exit 1
    fi
    cd $DESTDIR

    if [ -s "$FILELIST" ]
    then
	CPIOFILES=`cat $FILELIST`
    else
    	CPIOFILES=
    fi

    if [ -z "$CPIOFILES" ]
    then
    	echo "Extracting entire contents of tape" | tee -a $AUDITLOG
	tcio -i $MEDIADEV | cpio -idvu | tee -a $AUDITLOG
    else
        if [ -z "$MEDIADEV" ]
        then
            echo ""
            echo "Please supply device name..."
            echo ""
            echo "      Ex. INSTALL -m tcio -f /dev/rct/rc1"
            echo ""
	    cd $PWD
            exit 1
 	else
	    awk '{
		if (NF > 0) {
		    printf ("rm -rf %s/*\n", $1);
		    printf ("tcio -i %s | cpio -idvu %s/* \n", dev, $1);
		}
	    }' dev=$MEDIADEV $FILELIST | sh
	fi
    fi

    cd $PWD
fi

exit 0

