#!/usr/bin/python3 -Bsu

from pathlib import Path
import sys

# Allow terminating with Ctrl+C even when reading a file
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

#print "No matches found.\n";
#print "Match found at offset $pos.\n";

def print_usage():
    print("str_match: Usage: str_match Search File")
    print("str_match: Or: STDIN str_match Search")

def main(search_str, source_file=None):
    if source_file is not None and Path(source_file).is_dir():
        print("str_match: Error: '{0}' is a directory, not a file".format(source_file))
        sys.exit(1)

    try:
        if source_file is not None:
            with open(source_file, "r") as source_fh:
                input_data = source_fh.read()
        else:
            input_data = sys.stdin.read()

        if not input_data:
            print("str_match: Error: No input provided.")
            sys.exit(1)

        if search_str in input_data:
            print("str_match: Match found.")
            sys.exit(0)
        else:
            print("str_match: No matches found.")
            sys.exit(1)

    except FileNotFoundError:
        print(f"str_match: Cannot open the file '{source_file}'")
        sys.exit(1)

    except IOError as e:
        print(f"str_match: Error reading the file: {e}")
        sys.exit(1)

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print_usage()
        sys.exit(1)

    search_str = sys.argv[1]
    source_file = None
    if len(sys.argv) == 3:
        source_file = sys.argv[2]
    elif len(sys.argv) > 3:
        print_usage()
        sys.exit(1)

main(search_str, source_file)
