#!/bin/bash
BROWSER_BIN="${BROWSER_BIN}";
EXTENSION_NAME="${EXTENSION_NAME}";
UNPACKED_EXTENSION="${UNPACKED_EXTENSION}";
EXTENSION_DIR="${EXTENSION_DIR}";
EXTENSION_POLICY_DIR="${EXTENSION_POLICY_DIR}";

# Elevate script
if [ ! "$UID" -eq 0 ]
then
    sudo \
        BROWSER_BIN="${BROWSER_BIN}" \
        EXTENSION_NAME="${EXTENSION_NAME}" \
        UNPACKED_EXTENSION="${UNPACKED_EXTENSION}" \
        EXTENSION_DIR="${EXTENSION_DIR}" \
        EXTENSION_POLICY_DIR="${EXTENSION_POLICY_DIR}" \
        bash "$BASH_SOURCE" "$USER";
else
    keyFile="$UNPACKED_EXTENSION.pem";
    extensionFile="$UNPACKED_EXTENSION.crx";
    manifestFile="$UNPACKED_EXTENSION/manifest.json";

    destination="$EXTENSION_DIR/$EXTENSION_NAME.crx";

    sudo -u "$1" "${BROWSER_BIN}" --pack-extension="$UNPACKED_EXTENSION";

    # Tamper manifest file
    manifest="$(cat "$manifestFile" | jq ". + {key: "'"'"$(openssl rsa -in "$keyFile" -pubout -outform DER | openssl base64 -A)"'"'"}")";
    echo "$manifest" | sudo -u "$1" tee "$manifestFile";

    # Pack extension
    extensionID="$(openssl rsa -in "$keyFile" -pubout -outform DER | sha256sum | head -c32 | tr 0-9a-f a-p)";
    extensionVersion="$(cat "$manifestFile" | jq -r '.version')";
    sudo -u "$1" "${BROWSER_BIN}" --pack-extension="$UNPACKED_EXTENSION" --pack-extension-key="$keyFile";

    # Install extension and preinstall it
    mkdir -p "$EXTENSION_DIR";
    cp "$extensionFile" "$destination";
    chmod -R a+rx "$EXTENSION_DIR";
    chmod -R u+w "$EXTENSION_DIR";
    mkdir -p "$EXTENSION_POLICY_DIR";
    crxProperty="external_crx";

    find "$EXTENSION_POLICY_DIR" -name "*.json" -print0 |
        while IFS= read -r -d "" file
        do
            if [ "$(cat "$file" | jq -r ".$crxProperty")" == "$destination" ]
            then
                rm "$file";
            fi;
        done;

    {
        echo "{";
        echo '    "external_crx": "'"$destination"'",';
        echo '    "external_version": "'"$extensionVersion"'"';
        echo "}";
    } | tee "$EXTENSION_POLICY_DIR/$extensionID.json";
fi