#!/usr/bin/env python3

import os
import sys
import hashlib

def show_help():
    print("Usage: transhell_creator.py <script_file> [language_code] ...")
    print("")
    print("功能：遍历指定的shell脚本文件，抽取所有transhell函数调用中的字符串，然后生成或更新.transhell文件")
    print("")
    print("参数：")
    print("  <script_file>   要处理的shell脚本文件")
    print("  [language_code] 要生成的语言代码，可以指定多个")
    print("")
    print("Example: transhell_creator.py myscript.sh en_US zh_CN")
    print("")
    sys.exit(1)

def extract_strings(script_file):
    with open(script_file, 'r', encoding='utf-8') as file:
        content = file.read()
    return set(part[1] for part in [line.split('transhell') for line in content.splitlines() if 'transhell' in line] if len(part) > 1)

def create_or_update_transhell_file(script_file, lang, strings):
    transhell_dir = os.path.join(os.path.dirname(script_file), 'transhell')
    os.makedirs(transhell_dir, exist_ok=True)
    transhell_file = os.path.join(transhell_dir, f"{os.path.basename(script_file)}_{lang}.transhell")

    existing_translations = {}
    if os.path.exists(transhell_file):
        with open(transhell_file, 'r', encoding='utf-8') as file:
            lines = file.readlines()
        for i in range(0, len(lines), 2):
            key = lines[i + 1].split('=')[0]
            existing_translations[key] = lines[i + 1].strip()

    with open(transhell_file, 'w', encoding='utf-8') as file:
        for string in strings:
            uuid = f"transhell_{hashlib.md5(string.encode('utf-8')).hexdigest()}"
            if uuid not in existing_translations:
                file.write(f"# {string}\n{uuid}=\"{string}\"\n")
            else:
                file.write(f"# {string}\n{existing_translations[uuid]}\n")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        show_help()

    script_file = sys.argv[1]
    lang_codes = sys.argv[2:]

    if not os.path.isfile(script_file):
        print(f"Error: Script file {script_file} not found!")
        show_help()

    strings = extract_strings(script_file)
    for lang in lang_codes:
        create_or_update_transhell_file(script_file, lang, strings)

    print("Transhell files have been successfully created/updated.")

