#!/usr/bin/python3

import sys
from os import walk, path
import argparse
import subprocess
from colorama import Fore, Style


import logging
from rich.logging import RichHandler
from rich import print
from csifter.sifter import sift

'''
  ____ ____ ___ _____ _____ _____ ____  
 / ___/ ___|_ _|  ___|_   _| ____|  _ \ 
| |   \___ \| || |_    | | |  _| | |_) |
| |___ ___) | ||  _|   | | | |___|  _ < 
 \____|____/___|_|     |_| |_____|_| \_\

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

 ‣ A poormans static analyser for C source
   audits
 ‣ Written badly in python  
 ‣ Do not trust this tool beyond identifying
   the most basic of potential vulnerabilities
  ‣ Some of the logic here features awful code 
    reuse and needs refactoring
'''

def main(args):
	""" for each file supplied sift """
	if (args.path is not None): 
		sift_path(args.path, args.limit, args.no_warn);
		return

	for file in args.files:
		try:
			print(f'[bold][>->][/bold] Sifting sauce for [b green]{file}\n')
			sift(file, args.limit, args.no_warn)
		except FileNotFoundError:
			print(f'[bold][>->][/bold] File [b red]{file} not found[/b red], skipping\n')


def sift_path(target_path, limit=None, no_warn=False):
	""" sift all files in a directory """
	for root, dir, files in walk(target_path):
		for file in files:
			if(file.endswith('.c') or file.endswith('.h')):
				file_path = path.join(root, file)
				print(f'\n[bold][>->][/bold] Sifting sauce for [b green]{file_path}\n')
				sift(file_path, limit, no_warn)


def print_banner():
	print('''[bold red]
  ____ ____ ___ _____ _____ _____ ____      
 / ___/ ___|_ _|  ___|_   _| ____|  _ \     
| |   \___ \| || |_    | | |  _| | |_) |    
| |___ ___) | ||  _|   | | | |___|  _ <     
 \____|____/___|_|     |_| |_____|_| \_\    

 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>                          
	[/bold red]''')


if __name__ == "__main__":

	parser = argparse.ArgumentParser(
		description=print_banner(), 
		epilog=">> Should have gone to stacksavers ?"
	)

	parser.add_argument('-f', '--files',
						nargs='+',
						dest='files',
						help = 'file(s) to audit',
						)
  
	parser.add_argument('-p', '--path',
						  dest='path',
						  help='path to audit'
						)
	
	parser.add_argument('-l', '--limit',
						dest='limit',
						default=None,
						type=int,
						help='''
						limit the number of results 
						returned at once (per file)
						'''
	) 
	parser.add_argument('-r', '--risks',
						dest='no_warn',
						action='store_true',
						help='only report risks, exclude warnings'
	) 

	args = parser.parse_args()

	if (len(sys.argv) == 1): parser.print_help()
	else: main(args)

