#!/usr/bin/python3 -su

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)

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

def main(search_str, replace_str, source_file=None):
    source_fh = None

    if source_file is not None and Path(source_file).is_dir():
        print("ERROR: '{0}' is a directory, not a file".format(source_file))
        sys.exit(1)

    try:
        if source_file is not None:
            source_fh = open(source_file, "r+")
        else:
            source_fh = sys.stdin

        file_data = source_fh.read()
        file_data = file_data.replace(search_str, replace_str)

        if source_file is not None:
            source_fh.seek(0)
            source_fh.truncate()
            source_fh.write(file_data)
            source_fh.close()
        else:
            sys.stdout.write(file_data)

    except IOError as e:
        print("ERROR: {0}".format(e))
        sys.exit(1)

    except UnicodeDecodeError:
        print(f"ERROR: File '{source_file}' is not valid UTF-8.")
        sys.exit(1)

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

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

main(search_str, replace_str, source_file)
