#!/bin/bash

cd "$(dirname $0)/.."

version="$2"

if [[ -z "$version" ]]; then
  current=$(grep '"version":' src/drivers/webextension/manifest.json | sed 's/^.*"version": "\(.*\)".*$/\1/')

  echo "No version specified. Current version is $current."

  exit 1;
fi

set -eu

./bin/validate

echo "Deleting junk files..."

find . -name ".DS_Store" -exec rm {} \;

echo "Prettifying apps.json..."

sed -e 's/\\\\/{{ESCAPE}}/g' src/apps.json | jsonlint-cli -ps | sed -e 's/{{ESCAPE}}/\\\\/g' > /tmp/apps.json && cat /tmp/apps.json > src/apps.json

echo "Converting SVG icons to PNG..."

svg2png-many -i src/icons/ -o src/icons/converted/ --width=32 --height=32

echo "Compressing PNG icons..."

set +e

optipng -quiet "src/icons/*.png"
optipng -quiet "src/icons/converted/*.png"

set -e

# NPM
sed -i "s/\"version\": \"[^\"]*\"/\"version\": \"$version\"/" src/drivers/npm/package.json

# WebExtension
echo "Building WebExtension..."

webextension_dir=src/drivers/webextension

pushd $webextension_dir > /dev/null

sed -i "s/\"version\": \"[^\"]*\"/\"version\": \"$version\"/" manifest.json

zip -qr ../../../build/wappalyzer_webextension.zip . \
  -x images/icon_44.png \
  -x images/icon_50.png \
  -x images/icon_150.png \
  -x js/ms_\*.js \
  -x \*.log \
  -x \*.lock \
  -x \*.gitignore \
  -x \*.gitkeep \
  -x \*.js.map \
  -x \*.min.js \
  -x \*.spec.js \
  -x \*.yarn-integrity \
  -x \*package.json \
  -x \*LICENSE \
  -x \*README.md

popd > /dev/null

echo "Done (v$version)."
