#!/usr/bin/env python3

#Count files and directories from the current directory. This is not recursive. See countr for that.

"""
Copyright ~2024 Mark

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""

import glob, os, subprocess, sys;

def count_files(directory, ext, recursive=False):
    files=None;
    if recursive==False:
        files = glob.glob(os.path.join(directory, ext));
    else:
        pattern = os.path.join(directory, '**', f'*{ext}');
        files = glob.glob(pattern, recursive=True);
    files=set(files); #This is important because there are duplicates when recursive here (don't ask me why).
    file_count=0;
    folder_count=0;
    ext_dict={};
    for file in files:
        if os.path.isdir(file):
            folder_count+=1;
        elif os.path.isfile(file):
            file_count+=1;
            file_ext=os.path.splitext(file)[1];
            if file_ext=="":
                file_ext="(No extension)";
            if file_ext not in ext_dict:
                ext_dict[file_ext]=1;
            else:
                ext_dict[file_ext]+=1;
    """
    if ext=="*":
        subprocess.run("ls", shell=True);
    else:
        subprocess.run("ls "+ext, shell=True);
    """
    print("Directory count: "+str(folder_count));
    print("File count: "+str(file_count));
    for k,v in ext_dict.items():
        print(k+": "+str(v));

if __name__ == "__main__":
    current_directory = os.getcwd();
    recursive=False;
    try:
        ext=sys.argv[1];
        #count_files(current_directory, ext, recursive);
        print("Arguments are disabled.");
    except IndexError:
        count_files(current_directory, "*", recursive);