#!/bin/bash
# script to modify the content of a .zip file

sourcefile=$1
modifytarget=$2

tmpzip="/tmp/modzip$RANDOM-tmp.zip"
tmpdir="/tmp/modzip$RANDOM"

selfpath=$(readlink -f $0)
#on Solaris or with missing readlink set selfpath manually (example follows, uncomment if required)
#selfpath="/your/path/to/modzip.sh"

# recursion funtion for zip in a zip case
function zip_in_zip {
	while true; do
            read -p "Target is a zip. (M)odify, (L)ist or e(x)it? " choice
            case $choice in
                [Mm]* ) read -p "What file inside $modifytarget ?" mod_in_zip; $selfpath $modifytarget $mod_in_zip; break;;
                [Ll]* ) unzip -l $modifytarget;;
                [Xx]* ) break;;
                * ) echo "Type 'M' to modify zip file content, 'L' for listing zip content,'X' for exit this script";;
            esac
        done
} 


# MAIN CODE

# checking parameters and source file
if [ ! -f $sourcefile ]
then #first check if source zip file exists & is a regular file
	echo 'The source zip file does not exist or is a device or folder.'
	exit 1
elif [[ ("$#" == 1 ) ]] 
then
	echo 'Here comes the content of your file:'
	unzip -l $sourcefile
fi
if [[ ! ("$#" == 2 ) ]] 
then 
	echo '--------------------------------------'    	
	echo 'Use this script with following syntax: "./modzip.sh /path/to/my/source.zip filename-inside-the-zip.txt"'
    	exit 1
fi

# extracting zip to tmp folder
cp $sourcefile $tmpzip
unzip -q -d $tmpdir $tmpzip
cd $tmpdir

#check if file exists inside the archive
if [ ! -f "$modifytarget" ]
then
	echo "File $modifytarget does not exist in the given zip file or is a folder or device."
	#clean upi and exit
	rm -rf $tmpzip $tmpdir
	exit 1
fi
#what kind of file are we going to modify
case "${modifytarget##*.}" in
     log)
	less $modifytarget
	;;
     txt)
	vi $modifytarget
	;;
     xml)
	vim $modifytarget
	;;
     jar)
	#zip file in a zip file           
	zip_in_zip	
        ;;
     sar)
	#zip file in a zip file 
        zip_in_zip
	;;
     zip)
	#zip file in a zip file 
        zip_in_zip
	;;
     *)
	echo "Format not recognized. Please adapt this script for a default action. Trying to open with vi now."
	sleep 3;
	vi $modifytarget
	exit
	;;
esac          

#write back the changes to tmp zip
zip -r -u $tmpzip *
#write back changed archive to source
cd - > /dev/null
cp $tmpzip $sourcefile
#clean up
rm -rf $tmpzip $tmpdir


