#!/usr/bin/env python3
"""
生成文件校验和（MD5 / SHA256），输出为 MD5SUMS 或 SHA256SUMS 文件。
用法: genchecksum --md5|--sha256 <文件路径>
"""

import sys
import os
import subprocess
import hashlib


def notify(title, message, icon="emblem-checked"):
    subprocess.run([
        "notify-send",
        "--app-name=生成校验和",
        title,
        message,
        f"--icon={icon}"
    ])


def compute_checksum(filepath, algo):
    h = hashlib.new(algo)
    with open(filepath, "rb") as f:
        while True:
            chunk = f.read(8192)
            if not chunk:
                break
            h.update(chunk)
    return h.hexdigest()


def main():
    try:
        if len(sys.argv) < 3:
            notify("", "失败", "dialog-error")
            sys.exit(1)

        algo_flag = sys.argv[1]
        filepath = sys.argv[2]

        if algo_flag == "--md5":
            algo = "md5"
            ext = ".md5"
        elif algo_flag == "--sha256":
            algo = "sha256"
            ext = ".sha256"
        else:
            notify("", "失败", "dialog-error")
            sys.exit(1)

        if filepath.startswith("file://"):
            filepath = filepath[7:]

        if not os.path.isfile(filepath):
            notify("", "文件不存在", "dialog-error")
            sys.exit(1)

        digest = compute_checksum(filepath, algo)
        filename = os.path.basename(filepath)
        sumfile = filepath + ext

        with open(sumfile, "w") as f:
            f.write(f"{digest}  {filename}\n")

        notify("", f"已生成 {filename}{ext}", "emblem-checked")

    except Exception:
        notify("", "失败", "dialog-error")
        sys.exit(1)


if __name__ == "__main__":
    main()
