#!/bin/bash
SUCCESS="\033[32m"
ERROR="\033[31m"
NC="\033[0m"

project_repository="fix"
project_directory=$(pwd)
fixFile=$1

cd ..
mkdir tmp
cd tmp
git clone https://github.com/quickfixgo/quickfix

# Get the current working directory
tmp_directory=$(pwd)
# Set the folder path dynamically
cloned_repo="$tmp_directory/quickfix"


if [ -d "$cloned_repo" ]; then
    cd quickfix

    last_update=$(git log -1 --format=%cd)
    existing_update=$(cat "$project_directory/last_update_info.txt")

    if [ "$existing_update" = "$last_update" ]; then
        echo -e "${SUCCESS}The library is already updated, there are no new changes in the repository${NC}"

        # delete tmp folder
        rm -rf "$tmp_directory"

        exit 0
    fi

    # replace the fix file in the project
    rm spec/$fixFile
    cp $project_directory/spec/$fixFile spec/$fixFile

    # generate the library code
    make
    make generate

    # rename go.mod and go.sum
    mv go.mod go.mod_
    mv go.sum go.sum_

    # update the last update date
    echo "$last_update" > $project_directory/last_update_info.txt
    echo -e "${SUCCESS}Last update information has been updated in last_update_info.txt${NC}"

    echo "Clearing existing contents of $project_directory/quickfix..."
    rm -rf "$project_directory/quickfix"/*

    echo "Copying new contents to $project_directory/quickfix..."
    cp -R "$cloned_repo/"* "$project_directory/quickfix"

    # delete tmp folder
    rm -rf "$tmp_directory"

    #replace library imports
    cd $project_directory
    find quickfix -type f -exec sed -i '' 's|github.com/quickfixgo/quickfix|quantex.com/qfixdpl/quickfix|g' {} +

    echo "Library Updated"
else
    echo -e "${ERROR}Could not clone the repo${NC}"
    # delete tmp folder
    rm -rf "$tmp_directory"
    exit 1
fi