#!/usr/bin/env python3

import os,sys,re

print("Input argument is %s" %(sys.argv[1:]))

arguments = sys.argv[1:]
if (len(arguments) != 1):
    print("Arguments Invalid!")
    sys.exit()

newrepo = sys.argv[1]
print(f"upgrade castbox library to {newrepo}")

# Get the current directory
current_dir = os.getcwd()
# git@git.chengdu.pundit.company:castbox/guru_sdk.git
# 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"(.*url: )(.*guru_app.*)(\n.*)(ref:.*)\n", fr'\1{newrepo}\3path: guru_app\3\4', filedata)
            filedata = re.sub(fr"(.*url: )(.*guru_ui.*)(\n.*)(ref:.*)\n", fr'\1{newrepo}\3path: guru_ui\3\4', filedata)
            filedata = re.sub(fr"(.*url: )(.*guru_app.*)(\n.*path: )(.*)\n", fr'\1{newrepo}\3guru_app/\4\n', filedata)
            filedata = re.sub(fr"(.*url: )(.*guru_ui.*)(\n.*path: )(.*)\n", fr'\1{newrepo}\3guru_ui/\4\n', filedata)
            # Write the file out again
            with open(file_path, 'w') as file:
                file.write(filedata)
                print(f"Upgrade Completed => {file_path}")
