#!/bin/bash

usage() {
	echo "$0 <FILENAME.xpi>"
}


# Retrieve the extension id for an addon from its install.rdf
get_extension_id() {
  unzip -qc $1 install.rdf | xml sel \
    -N rdf=http://www.w3.org/1999/02/22-rdf-syntax-ns# \
    -N em=http://www.mozilla.org/2004/em-rdf# \
    -t -v \
    "//rdf:Description[@about='urn:mozilla:install-manifest']/em:id"
}

XPI_FILE="$1"

if ! [ -r "$XPI_FILE" ]; then
	echo "failed to read file $XPI"
	usage
	exit 1
fi

XPI_ID=`get_extension_id $XPI_FILE`

if [ -z "$XPI_ID" ]; then
	echo "failed to determine XPI ID from file $XPI_FILE"
	exit 1
fi

echo "ID: $XPI_ID"
#mkdir $XPI_ID && cd $XPI_ID && unzip $XPI_FILE || {
unzip $XPI_FILE -d $XPI_ID && chmod -R a+x $XPI_ID || {
	echo "failed to extract file $XPI_FILE to $PWD/$XPI_ID"
	exit 1
}

