#!/bin/bash

LATEST_GCC_WORKING_VERSION=14
PATH_TO_BUILD_CONFIG=~/.local/share/cargo/registry/src/index.crates.io-1949cf8c6b5b557f/librocksdb-sys-0.11.0+8.1.1/build.rs
GCC_MAJOR=$(gcc -dumpversion | cut -d. -f1)

SKIPPED_PATCH_OK="[+] patch-3 not needed: gcc version is good to compile without patch"
[[ "$GCC_MAJOR" -le "$LATEST_GCC_WORKING_VERSION" ]] && { echo $SKIPPED_PATCH_OK; exit 0; }

SKIPPED_PATCH_OK="[+] patch-3 already applied: no need to change build config of librocksdb"
grep -q "config.flag(\"-include\").flag(\"cstdint\");" "$PATH_TO_BUILD_CONFIG" && { echo $SKIPPED_PATCH_OK; exit 0; }

PATCH_MESSAGE="include cstdint for build config of librocksdb"
[[ -z "$1" ]] && { echo "[!] patch-3 could be applied: $PATCH_MESSAGE"; exit 2; }

sed -i "/$(printf '%s' "config.compile(\"librocksdb.a\");" | sed 's/[].[*^$\/]/\\&/g')/i \
    if !target.contains(\"windows\") {\n        config.flag(\"-include\").flag(\"cstdint\");\n    }" "$PATH_TO_BUILD_CONFIG"
echo "[+] patch-3 will be applied: $PATCH_MESSAGE"
exit 0
