#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
INSTALL_DIR="${ROOT_DIR}/dist"
SRC_ADDON_DIR="${ROOT_DIR}/addon"
ADDON_XML="${SRC_ADDON_DIR}/addon.xml"

if [[ ! -f "${ADDON_XML}" ]]; then
  echo "Missing: ${ADDON_XML}" >&2
  exit 1
fi

ADDON_ID="$(python3 - "${ADDON_XML}" <<'PY'
import sys
import xml.etree.ElementTree as ET

tree = ET.parse(sys.argv[1])
root = tree.getroot()
print(root.attrib.get("id", "plugin.unknown"))
PY
)"

ADDON_VERSION="$(python3 - "${ADDON_XML}" <<'PY'
import sys
import xml.etree.ElementTree as ET

tree = ET.parse(sys.argv[1])
root = tree.getroot()
print(root.attrib.get("version", "0.0.0"))
PY
)"

ZIP_NAME="${ADDON_ID}-${ADDON_VERSION}.zip"
ZIP_PATH="${INSTALL_DIR}/${ZIP_NAME}"

ADDON_DIR="$("${ROOT_DIR}/scripts/build_install_addon.sh" >/dev/null; echo "${INSTALL_DIR}/${ADDON_ID}")"

rm -f "${ZIP_PATH}"
python3 "${ROOT_DIR}/scripts/zip_deterministic.py" "${ZIP_PATH}" "${ADDON_DIR}" >/dev/null

echo "${ZIP_PATH}"
