# Check for handle argument
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 handle"
    exit 1
fi

# Assign the handle argument to a variable
HANDLE=$1

# Define the languages directory
LANG_DIR="languages"

# Install / update po2json
npm install @myrotvorets/po2json

# Verify languages directory exists
if [ ! -d "$LANG_DIR" ]; then
    echo "The directory '$LANG_DIR' doesn't exist. Please run this script in the main plugin folder."
    exit 2
fi

# Change directory to languages directory
cd "$LANG_DIR"

# Iterate over all .po files in the languages directory
for po_file in *.po; do
    # Extract the domain and locale from the filename by removing the file extension
    FILENAME=$(basename -- "$po_file" .po)
    
    # Construct the output json file name
    JSON_FILE="${FILENAME}-${HANDLE}.json"
    
    # Run po2json conversion
    npx po2json "$po_file" > "$JSON_FILE"
    echo "Generated $JSON_FILE from $po_file"
done

# Change back to main plugin directory
cd ..