import os,sys,re

print("Input argument is %s" %(sys.argv[1:]))
gitrepo = ""
version = ""
arguments = sys.argv[1:]
if (len(arguments) != 2):
    print("Arguments Invalid!")
    sys.exit()

gitrepo = sys.argv[1]
version = sys.argv[2]
print(f"upgrade {gitrepo}.git library to {version}")

# Get the current directory
current_dir = os.getcwd()

# Iterate through all files in the directory
for dirpath, dirnames, filenames in os.walk(current_dir):
    # Check if the file is a pubspec.yaml file
    for filename in filenames:
        if filename == "pubspec.yaml":
            # Open the pubspec.yaml file
            file_path = os.path.join(dirpath, filename)
            with open(file_path, 'r') as file:
                # Read the contents of the file
                filedata = file.read()

            # Replace the ref value for the libraries with git link that contains "example.com"
            filedata = re.sub(fr"(.*git:.*\n.*url.*{gitrepo}.*\n.*path:.*\n.*)(ref: .*)", fr"\1ref: {version}", filedata)
            filedata = re.sub(fr"(.*git:.*\n.*url.*{gitrepo}.*\n.*)(ref: .*)", fr"\1ref: {version}", filedata)
            # Write the file out again
            with open(file_path, 'w') as file:
                file.write(filedata)
                print(f"Upgrade Completed => {file_path}")
