#!/bin/sh

extpath=$1
xpi=$2

if [ -z "$extpath" ]; then
    echo "usage: $0 <mozilla extension path> [<xpi file>]"
    exit 1
fi

xpi_dir="."
if [ -n "$xpi" ]; then
    xpi_dir="`basename $xpi`.dir"
    rm -rf $xpi_dir
    mkdir -p $xpi_dir
    unzip -q -d $xpi_dir $xpi
fi

rdf="$xpi_dir/install.rdf"
if [ ! -f $rdf ]; then
    echo "unable to find rdf file"
    exit 1
fi

# remove leading newline from some broken rdf files (pt-PT)
perl -pi -e 's/^\r?\n// if $. == 1' $rdf

hash="$(perl -pe 's/\r\n/\n/g' $rdf | sed -n '/.*em:id="\(.*\)"/{s//\1/p;q}')"
if [ -z "$hash" ]; then
    hash="$(perl -pe 's/\r\n/\n/g' $rdf | sed -n '/.*em:id>\(.*\)<\/em:id>.*/{s//\1/p;q}')"
fi
if [ -z "$hash" ]; then
    echo "Failed to find plugin hash."
    exit 1
fi

echo "installing $hash in $extpath"

extdir="$extpath/$hash"
rm -rf $extdir
mkdir -p "$extdir"
cp -af $xpi_dir/* "$extdir/"

if [ -n "$xpi" ]; then
    rm -rf $xpi_dir
fi
