#! /usr/bin/python3

"Quarantine tool"

import sys
import os
import subprocess

cwd = os.getcwd()

def gethomedir(filename):
    bits=filename.split('/')
    # ''
    # home
    # username
    if len(bits)<4: return None
    if bits[1]=='home': return '/'.join(bits[:3])
    if bits[2]=='home': return '/'.join(bits[:4])
    return None

def mkdir_p(targetdir,reference,startdepth=3):
    bits=targetdir.split('/');
    for bittie in range(startdepth,len(bits)+1):
        part = '/'.join(bits[:bittie])
        if not os.path.exists(part):
            subprocess.call(['mkdir', part ])
            subprocess.call(['chown', '--reference='+reference, part ])

def quarantine(filename, unquarantine=False):
    filename=filename.rstrip("/\n");
    filename=filename.replace('//','/');
    filename=filename.replace('/./','/');
    if not filename:
        return
    if not os.path.exists(filename):
        sys.stderr.write('%s: not found\n'% filename);
        return
    if not filename.startswith('/'):
        filename=cwd+'/'+filename
    homedir=gethomedir(filename);
    if not homedir:
        sys.stderr.write('%s: not in /home/\n'% filename);
        return
    quarantinedir=homedir+'/quarantine'
    targetdir = os.path.dirname(quarantinedir+filename)
    if not os.path.exists(targetdir):
        mkdir_p(targetdir,filename);
        # TODO: set ownership and permission ...
        # os.system(['chown', '--reference=', os.path.dirname(targetdir), ])
    subprocess.call(['mv', '-v', '--backup=numbered', filename, quarantinedir+filename, ])


if __name__=="__main__":
    import optparse
    parser=optparse.OptionParser()
    parser.add_option("-u","--unquarantine", dest="unquarantine", action="store_true", default=False, help="Reverse what we did")
    parser.add_option("-v","--verbose", dest="verbose", action="count", default=0, help="How verbose")
    (options,file_list) = parser.parse_args()

    unquarantine=options.unquarantine

    for val in file_list:
        if val=='-u':
            unquarantine=True
            file_list.remove(val)

    if len(file_list)==0:
        file_list=sys.stdin
        if sys.stdin.isatty(): sys.stderr.write("Type the names of the files to quarantine, one per line:\n");

    for filename in file_list:
        quarantine(filename)
