#!/bin/bash

LATEST_TESTED_VERSION=83
MANIFEST_PATH=$(cargo metadata --format-version 1 | python3 -c "
import sys,json
data = json.load(sys.stdin)
for pkg in data['packages']:
    if pkg['name'] == 'sp-io':
        print(pkg['manifest_path'])
        break
")
DEPENDENCY_PATH="${MANIFEST_PATH%Cargo.toml}src/lib.rs"

SKIPPED_PATCH_OK="[+] patch-2 not needed: rustc compiler version is compatible"
cargo_version=$(cargo --version | cut -d'.' -f2)
[[ "$cargo_version" -le "$LATEST_TESTED_VERSION" ]] && { echo $SKIPPED_PATCH_OK; exit 0; }

SKIPPED_PATCH_OK="[+] patch-2 already applied: #[no_mangle] already removed from source code of sp-io"
! grep -q '#\[no_mangle\]' "$DEPENDENCY_PATH" && { echo $SKIPPED_PATCH_OK; exit 0; }

PATCH_MESSAGE="remove unnecessary #[no_mangle] from the source code for sp-io"
[[ -z "$1" ]] && { echo "[!] patch-2 could be applied: $PATCH_MESSAGE"; exit 2; }

echo "[+] patch-2 will be applied: $PATCH_MESSAGE"
sed -i '/#\[no_mangle\]/d' "$DEPENDENCY_PATH"
exit 0
