#!/bin/bash
# This script generates the ContentBlockerConverterVersion.swift file with
# library and component versions.
# Usage: ./scripts/make/codegen.sh <LIBRARY_VERSION>

set -e

if [ $# -ne 1 ]; then
    echo "Usage: $0 <LIBRARY_VERSION>"
    exit 1
fi

LIB_VERSION="$1"
PACKAGE_JSON="$(dirname "$0")/../../Extension/package.json"
OUTPUT_DIR="$(dirname "$0")/../../Sources/ContentBlockerConverter"
OUTPUT_FILE="$OUTPUT_DIR/ContentBlockerConverterVersion.swift"

if [ ! -f "$PACKAGE_JSON" ]; then
    echo "package.json not found at $PACKAGE_JSON"
    exit 1
fi

# Set the version field in package.json to LIB_VERSION
TMP_PKG_JSON="$PACKAGE_JSON.tmp"
jq --arg ver "$LIB_VERSION" '.version = $ver' "$PACKAGE_JSON" >"$TMP_PKG_JSON" && mv "$TMP_PKG_JSON" "$PACKAGE_JSON"

echo "Set version in $PACKAGE_JSON to $LIB_VERSION"

# Extract versions using jq
SCRIPTLETS_VERSION=$(jq -r '.dependencies["@adguard/scriptlets"]' "$PACKAGE_JSON" | sed 's/^\^//')
EXTENDEDCSS_VERSION=$(jq -r '.dependencies["@adguard/extended-css"]' "$PACKAGE_JSON" | sed 's/^\^//')

if [ -z "$SCRIPTLETS_VERSION" ] || [ "$SCRIPTLETS_VERSION" == "null" ]; then
    echo "@adguard/scriptlets version not found in package.json"
    exit 1
fi
if [ -z "$EXTENDEDCSS_VERSION" ] || [ "$EXTENDEDCSS_VERSION" == "null" ]; then
    echo "@adguard/extended-css version not found in package.json"
    exit 1
fi

mkdir -p "$OUTPUT_DIR"

cat <<EOF >"$OUTPUT_FILE"
// This file is auto-generated by scripts/make/codegen.sh. Do not edit manually!

/// Version information for the SafariConverterLib and its components. It can be
/// used in the apps that are using this library.
public enum ContentBlockerConverterVersion {
    /// Version of SafariConverterLib and @adguard/safari-extension.
    public static let library = "$LIB_VERSION"

    /// Version of @adguard/scriptlets (component of the JS library).
    public static let scriptlets = "$SCRIPTLETS_VERSION"

    /// Version of @adguard/extended-css (component of the JS library).
    public static let extendedCSS = "$EXTENDEDCSS_VERSION"
}
EOF

echo "Generated $OUTPUT_FILE"
