#!/usr/bin/env python
"""
Script to search and display the content of all ".DS_Store" files present in a folder.

Sources:
    https://github.com/dmgbuild/ds_store
    https://metacpan.org/dist/Mac-Finder-DSStore/view/DSStoreFormat.pod

Dependency: pip install termcolor ds-store tabulate
"""
import argparse
from pathlib import Path
from termcolor import colored
from ds_store import DSStore
from tabulate import tabulate

REF_NAME = ".DS_Store"


def print_file_entries(dsstore_file_path):
    print(colored(f"File: {dsstore_file_path}", "cyan"))
    try:
        with DSStore.open(dsstore_file_path, "r+") as d:
            if d._records == 0:
                print(f"No content")
            else:
                data = []
                data.append(["Code", "Type", "Filename", "Value"])
                for entry in d._traverse(None):
                    data.append([entry.code, entry.type, entry.filename, entry.value])
                print(tabulate(data, headers="firstrow", tablefmt="github"))
    except Exception as e:
        print(colored(f"[!] Error: {str(e)}", "red"))


def find_files(folder_path):
    files = []
    for path in Path(folder_path).rglob(REF_NAME):
        if path.name.endswith(REF_NAME):
            files.append(path.absolute().__str__().replace("\\", "/"))
    return files


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Script to search and display the content of all '.DS_Store' files present in a folder.")
    required_params = parser.add_argument_group("required named arguments")
    required_params.add_argument("-f", action="store", dest="base_folder", help="Path to the folder to use as base.", required=True)
    args = parser.parse_args()
    base_folder = args.base_folder
    print(colored(f"[+] Search for file '{REF_NAME}' in folder '{base_folder}' ...", "yellow"))
    files = find_files(base_folder)
    count = len(files)
    print(f"{count} file(s) found.")
    if count > 0:
        print(colored("[+] Display content.", "yellow"))
        for file in files:
            print_file_entries(file)
