#!/bin/bash

if [ $# != 1 ] ; then
echo "usage edbrowse-plugin-zip zipfile[path]"
exit 1;
fi

# We're going to generate <a> tags in html, with links that look like urls.
# the url holds the zip file and the path inside.
# If there are any odd characters in these paths, like < > or nonascii,
# and if we don't percent encode them here, edbrowse is going to do it for us.
# We have no choice.
# perl is the easiest way to encode and decode.

function uriEscape {
echo "$1" | perl -e 'use URI::Escape; my $s = <>; chomp $s; print uri_escape $s;'
}

function uriUnescape {
echo "$1" | perl -e 'use URI::Escape; my $s = <>; chomp $s; print uri_unescape $s;'
}

function htmlEscape {
echo "$1" | sed \
-e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g'
}

if [[ "$1" =~ @:@ ]] ; then
# this has been through our machinery and is encoded
# protocol is either zipx or zipxd
# zip file is before @:@, path is after
zf1="$1"
path1=${zf1/*@:@/}
zf1=${zf1/@:@*/}
zf=$(uriUnescape "$zf1")
path=$(uriUnescape "$path1")

#  check here for file extract
if [[ "$zf" =~ zipx: ]] ; then
zf=${zf/zipx:??/}
# the unzip command gives meaning to \, so we have to escape it
path=$(echo "$path" | sed 's/\\/\\\\/g')
unzip -p "$zf" "$path"
exit 0
fi

zf=${zf/zipxd:??/}
zf1=${zf1/zipxd:??/}
else
# first call, has not been encoded yet
path=
path1=
zf="$1"
zf1=$(uriEscape "$zf")
fi

# we're generating html, whence we can make links that edbrowse understands
echo "<body>Zip Archive"
if [ -z "$path" ] ; then
#  this is the root directory
unzip -t "$zf" |
sort |
sed -e '/testing:/!d' -e 's/^.*testing: *//' -e 's/  *OK$//' \
-e '/\/./d' \
-e 's/\\/\\\\/g' |
while read line; do
line1=$(uriEscape "$line")
prot=zipx
if [[ "$line" =~ / ]]; then prot=zipxd; fi
line2=$(htmlEscape "$line")
echo "<br><a href='$prot://$zf1@:@$line1'>$line2</a>"
done
else
# path as the left side of a sed expression
path_lhs=$(echo "$path" | sed 's/[",\\.*[]/\\&/g')
unzip -t "$zf" |
sort |
sed -e '/testing:/!d' -e 's/^.*testing: *//' -e 's/  *OK$//' \
-e "s,^$path_lhs,@:@," \
-e '/^@:@/!d' -e 's/^@:@//' \
-e '/^$/d' \
-e '/\/./d' \
-e 's/\\/\\\\/g' |
while read line; do
line1=$(uriEscape "$line")
prot=zipx
if [[ "$line" =~ / ]]; then prot=zipxd; fi
line2=$(htmlEscape "$line")
echo "<br><a href='$prot://$zf1@:@$path1$line1'>$line2</a>"
done
fi

echo "</body>"

exit 0
