import os

###############################################################################
# Overcomplicated script that increments the versionCode in build.gradle by 1 #
###############################################################################

script_path = os.path.dirname(os.path.realpath(__file__))

# open build.gradle as read
with open(script_path + "\\build.gradle", "r") as f:
    # read lines
    lines = f.readlines()

# find versionCode
for line_i in range(len(lines)):
    # find char_i of "project.ext.set("versionCode", "
    char_i = lines[line_i].find("project.ext.set(\"versionCode\",")

    if char_i != -1:
        char_i += 30

        line_max_i = len(lines[line_i]) - 1

        # find start of number
        while True:
            if char_i > line_max_i:
                print("Error: number in versionCode not found")
                input("Press Enter to exit...")
                exit()

            char_unicode = ord(lines[line_i][char_i])
            if 48 <= char_unicode <= 57:
                break
            char_i += 1
        
        # find end of number
        num_end_i = char_i + 1

        while True:
            char_unicode = ord(lines[line_i][num_end_i])
            if 48 > char_unicode or char_unicode > 57:
                break
            num_end_i += 1

        # get number
        num = int(lines[line_i][char_i:num_end_i])

        print(f"OLD versionCode: {num}")
        num += 1
        print(f"NEW versionCode: {num}")

        # replace number
        lines[line_i] = lines[line_i][:char_i] + str(num) + lines[line_i][num_end_i:]

        # write lines
        with open(script_path + "\\build.gradle", "w") as f:
            f.writelines(lines)

        break


if char_i == -1:
    print("Error: versionCode not found")
else:
    print("Done!")

input("Press Enter to exit...")
