#! /usr/bin/env python3.10

import jenkins, os

import xml.etree.ElementTree as ET
#connect
server = jenkins.Jenkins('https://man-dan-03:9443', username='JonnyBravo', password='113c3449636622439627ab1d51454fc07c')


def show_all_files_directory(dir_path = str, search_endung = False, search_string = False):
    li_all = []
    for root_folder, dirs, files in os.walk(dir_path, topdown=False):       
        for name in files: 
            FullPATH = str(os.path.join(root_folder, name))
            if not search_endung is False:
                if FullPATH.endswith(search_endung):
                    li_all.append(FullPATH)
            elif not search_string is False:
                if not FullPATH.find(search_string) ==  -1:
                     li_all.append(FullPATH)
            else:
                li_all.append(FullPATH)        
    return li_all


def show_all_directory(dir_path = str, search_endung = False, search_string = False):
    li_all = []
    for root_folder, dirs, files in os.walk(dir_path, topdown=False):       
        for name in dirs: 
            FullPATH = str(os.path.join(root_folder, name))
            #print(name)
            if not name.find(search_string) == -1:
                li_all.append(FullPATH)
    return li_all


def modify_jenkins_configfile(config_file_list = list):
    for config_file in config_file_list:
        config_file_FullPath = config_file
        print("open..." + config_file_FullPath)
        with open(config_file_FullPath , "r") as read_config:
            for line in read_config:
                print(line.rstrip("\n"))
        print("#" * len(config_file_FullPath))

def added_config_to_jenkins_xml(config_xml = str):
    xml_root = ET.parse(config_xml).getroot()   
    xml_str = ET.tostring(xml_root, encoding='utf8', method='xml').decode()
    
    for strategy in xml_root.findall('sources/data/jenkins.branch.BranchSource'):
        value = strategy.get('id')
        print(strategy.get('id'))
        print(value)



def main():
    #test = show_all_files_directory(dir_path=os.sep + "home" + os.sep + "jonnybravo" + os.sep + ".jenkins" + os.sep + "data" + os.sep + "jobs", search_string="config.xml")
    find_folder = show_all_directory(dir_path=os.sep + "home" + os.sep + "jonnybravo" + os.sep + ".jenkins" + os.sep + "data" + os.sep + "jobs", search_string="mulit")
    for config_file in find_folder:
        file = config_file + os.sep + "config.xml"
        print(file)
        added_config_to_jenkins_xml(file)
    #modify_jenkins_configfile(config_file_list=test)

if __name__ == "__main__":
    main()