#!/usr/bin/env bash

# Authors:
# Krzysztof Kotowicz - @kkotowicz - http://blog.kotowicz.net
#
# Unpacks a crx file, inject it with given payload, and, optionally
# packs it into zip/crx file
# see ../README.md

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

INPUT_CRX=$1
MODE=$2
DESTINATION=$3
JS_FILE=$4
shift 4

if [ ! -z "$1" ]; then # 5th param optional 
    PERMISSIONS=$1
    shift
else
    PERMISSIONS=""
fi

function help {
    printf "Usage: %s: <input.crx> <mode> <destination> <inject-bg.js> [permissions] [file1 ... ] \n" $(basename $0) >&2
    echo "         <input.crx> - original extension CRX file" >&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
}

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

if [ ! -f "${INPUT_CRX}" ]; then
    bailout "No input CRX file! - ${INPUT_CRX}"
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

function cleanup {
    rm -rf "$TMPDIR"
}

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

echo "Unpacking $INPUT_CRX to $EXTDIR..."
# supress warning about extra prefix bytes
unzip -qo "$INPUT_CRX" -d "$EXTDIR" 2>/dev/null
echo "Injecting script $JS_FILE..."

$DIR/inject.rb "$EXTDIR" "$PERMISSIONS" < $JS_FILE || bailout "Injection failed"

# copy additional files
for file in "$@"
do
    
    if [ -f "$file" ]; then
        echo "Adding $file..."
        cp "$file" "$EXTDIR"
    fi
done

echo "Mode: $MODE"

case "$MODE" in
    crx)
        if [ ! -x "$CHROMEPATH" ]; then
            bailout "You must set correct CHROMEPATH in tools/config.ini"
        fi

        echo "Signing $EXTDIR..."
        "$CHROMEPATH" --pack-extension="$EXTDIR" --pack-extension-key="$PEM" --no-message-box
        if (( $? )) ; then 
            bailout "Signing in Chrome FAILED." 
        fi

        echo "Moving signed extension to $DESTINATION"
        mv "`dirname "$EXTDIR"`/`basename "$EXTDIR"`.crx" "$DESTINATION"
        ;;
    zip)
        echo "Zipping extension to $DESTINATION"
        cd "$EXTDIR"
        zip -r __tmp.zip .
        cd -
        mv "$EXTDIR/__tmp.zip" $DESTINATION
        ;;
    dir)
        echo "Moving extension directory to $DESTINATION"
        rm -r "$DESTINATION"
        mv "$EXTDIR" "$DESTINATION"
        ;;
    *)
        bailout "Unknown mode: $MODE"
esac

cleanup
