#!/bin/bash -e

origdir=$1
xpifile=$2

error () {
	echo "$*" >&2
}

if [ -z "$xpifile" -o -z "$origdir" ]
then
	error "Usage: $0 origdir xpifile.xpi"
	exit 1
fi

if [ ! -d "$origdir" ]
then
	error "$origdir does not exist or is not a directory."
	exit 1
fi

if [ -x "$xpifile" ]
then
	error "$xpifile already exists."
	exit 1
fi

# ensure we delete all temporary stuff upon exit
olddir=`pwd`
trap 'rm -fR $tmpdir; cd $olddir' EXIT

# Copy all locale stuff into temporary directory
tmpdir=`mktemp -d`

cp -a $origdir/* $tmpdir
cd $tmpdir

# Cleanup
find . -name '*~' -o -iname '*.bak' -exec rm {} \;

# Determine the locale via the install.rdf file
locale=`cat install.rdf | sed -n 's/.*<Description about="urn:mozilla:extension:file:\([^.]\+\)\.jar.*/\1/p'`

if [ -z "$locale" ]
then
	error "The locale could not be determined."
	exit 1
fi
if [ "$locale" = "en-US" ]
then
	error "WARNING: locale is en-US (is this the translated tree?)"
fi

if [ -d locale/lang-reg ]
then
	mv locale/lang-reg locale/$locale
fi

mkdir chrome
zip -rD0 chrome/$locale.jar locale
rm -fR locale

# Build the XPI file and move it into $xpifile
cd $tmpdir
zip -r $locale.xpi *
cd $olddir
mv $tmpdir/$locale.xpi $xpifile
