#!/bin/bash

# ExtractFromZIP.bash
# Wed Dec 23 10:15:47 PST 2009
# Chieh Cheng
# http://www.CynosureX.com/

# GNU General Public License (GPL) Version 2, June 1991

  scriptDir=`dirname "$0"`
  scriptName=`basename "$0"`

function extractFiles ()
{
  archive="$1"
  tempFile="$2"
  matches=`cat "${tempFile}" | wc -l`

  echo "Found ${matches} matching files."

  while read line
  do
    filePath=`getFilePath "${line}"`
    unzip "${archive}" "${filePath}"
  done < "${tempFile}"
}

function getFilePath ()
{
  entry="$1"
  filePath=`echo "${entry}" | sed 's/^.*  [a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9]  //'`
  echo "${filePath}"
}

function locateFile ()
{
  archive="$1"
  file="$2"
  tempFile="$3"

  unzip -v "${archive}" | grep "${file}" >> "${tempFile}"
}

function usage ()
{
  echo "  Usage:   ${scriptName} \"ZIP archive\" \"file 1\" [ . . . \"file N\" ]"
}

function wrapUp ()
{
  tempFile="$1"

  while read line
  do
    filePath=`getFilePath "${line}"`
    location=`dirname "${filePath}"`

    if [ "${location}" != "." ] && [ -f "${filePath}" ]
    then
      mv "${filePath}" .
    fi
  done < "${tempFile}"

  while read line
  do
    filePath=`getFilePath "${line}"`
    location=`dirname "${filePath}"`

    if [ "${location}" != "." ] && [ -d "${location}" ]
    then
      rmdir -p "${location}"
    fi
  done < "${tempFile}"
}

  if [ $# -ge 2 ]
  then
    archive="$1"
    shift

    if [ -f "${archive}" ]
    then
      tempFile=`GetTempPathName.ksh "${scriptName}"`

      for file
      do
        locateFile "${archive}" "${file}" "${tempFile}"
        extractFiles "${archive}" "${tempFile}"
      done

      wrapUp "${tempFile}"

      rm "${tempFile}"
    else
      echo "${archive} does not exist!"
    fi
  else
    usage
  fi
