#!/usr/bin/env python3
import os
import sys
import subprocess


def secure_del(filename):
    """Securely delete file. Try using shred, if it doesnt exist perform a manual 3 pass overwrite"""

    if not os.path.exists(filename):  # Most secure delete ever
        raise("File doesn't exist: {}".format(filename))

    try:
        # -u deletes file after complete, -z zeroes the file at the end, hiding that it was shredded
        subprocess.run(["shred", "-uz", filename])
    except OSError:
        print("Shred is not available. Performing manual override.")
        f = None
        try:
            f = open(filename, "ab+")
            length = f.tell()      # Read each line of the file until the end
            for _ in range(0, 3):  # _ in python is short for a variable that isn't used
                f.seek(0)          # Move back to the start of the file
                f.write(os.urandom(length))  # Write garbage to file
        finally:
            if f is not None:
                f.close()
        os.remove(filename)
        return


# If this file is run, execute below.
# If this file is imported, run secure_del(filename)
if __name__ == "__main__":
    if len(sys.argv) != 2:
        exit("Usage: python secure_delete.py <filename>")

    secure_del(sys.argv[1])
