import os

def process_set_file():
    """
    Checks if /root/flowserver exists, reads set.txt, and modifies the second line.
    """
    default_folder = "/root/flowserver" if os.path.exists("/root/flowserver") else "/home/unipi/flowserver"
    flag = 1 if default_folder == "/root/flowserver" else 0

    try:
        with open("/home/unipi/flowserver/databases/settings.table", "r") as f:
            lines = f.readlines()

        if len(lines) >= 2:
            lines[0] = lines[0].rstrip('\n') + "|main_switch:boolean\n"
            second_line = lines[1].strip()  # remove trailing newline
            last_pipe_index = second_line.rfind("|")

            if last_pipe_index != -1:
                modified_line = second_line[:last_pipe_index + 1] + str(flag) + "|" + second_line[last_pipe_index + 1:]
                lines[1] = modified_line
            else:
                print("Warning: No '|' character found in the second line of set.txt")

            with open("/home/unipi/flowserver/databases/settings.table", "w") as f:
                f.writelines(lines)
        else:
            print("Warning: settings.table has less than two lines.")

    except FileNotFoundError:
        print("Error: settings.table not found.")
    except Exception as e:
        print(e)

# if __name__ == "__main__":
process_set_file()
