#!/bin/bash

# Check if the npm_package_version environment variable is set
if [ -z "$npm_package_version" ]; then
    echo "The npm_package_version environment variable is not set."
    exit 1
fi

# Run pnpm pack and capture its output
output=$(pnpm pack)

# Extract the last non-empty line from the output
filename=$(echo "$output" | grep -v '^$' | tail -n 1)

# Check if filename is not empty
if [ -n "$filename" ]; then
    # Run shasum with the filename and process the output through awk, xxd, and base64
    package_integrity=$(shasum -b -a 512 "$filename" | awk '{ print $1 }' | xxd -r -p | base64)

    # Construct the new string to replace in README.md
    new_string="\"build-scripts-allowlist\": \"$npm_package_version+sha512-$package_integrity\""
    # Escape special characters for sed
    escaped_new_string=$(printf '%s\n' "$new_string" | sed -e 's/[\/&]/\\&/g')

    # Use sed to replace the line in README.md
    if [[ "$OSTYPE" == "darwin"* ]]; then
        # macOS (BSD sed)
        sed -i '' "s/\"build-scripts-allowlist\": \".*\"/$escaped_new_string/" README.md
    else
        # Linux (GNU sed)
        sed -i "s/\"build-scripts-allowlist\": \".*\"/$escaped_new_string/" README.md
    fi


    echo "The string in README.md has been successfully updated."

    # Remove the file generated by pnpm pack
    rm "$filename"
    echo "The file $filename has been removed."
else
    echo "No filename found in pnpm pack output"
    exit 1
fi

git stash
echo "README.md updates stashed. Please publish the package first, then run"
echo "git stash pop"
