#!/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)

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):
    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:
            with open(source_file, "r+") as source_fh:
                file_data = source_fh.read()
                file_data = file_data.replace(search_str, replace_str)
                source_fh.seek(0)
                source_fh.truncate()
                source_fh.write(file_data)
        else:
            file_data = sys.stdin.read()
            file_data = file_data.replace(search_str, replace_str)
            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)
