#!/usr/bin/env python
import subprocess
import os
import time
import sys
from datetime import datetime

from .conf import settings


def get_hdinfo(path,value):
    return subprocess.check_output(["lsblk", path, "--nodeps", "-no", value]).strip()

def erase_disk(dev, erase_mode="0"):
    if erase_mode == "0":
        standard = "All zeros, low standard"
        iterations = "0"  # zero extra iterations (-z implies one)
    elif erase_mode == "1":
        standard = "Sector by sector, high standard"
        raise NotImplementedError
    
    FMT = "%Y-%m-%d %H:%M:%S"
    time_start = time.strftime(FMT)
    try:
        subprocess.check_call(["shred", "-zvn", iterations, dev])
        state = "Successful"
    except subprocess.CalledProcessError:
        state = "With errors."
        print "Cannot erase the hard drive '{0}'".format(dev)
    time_end = time.strftime("%Y-%m-%d %H:%M:%S")
    elapsed = datetime.strptime(time_end, FMT) - datetime.strptime(time_start, FMT)
    
    return {
        'erasure_standard_name': standard,
        'state': state,
        'elapsed_time': str(elapsed),
        'start_time': time_start,
        'end_time': time_end
    }

def do_erasure(sdx):
    print(
        "Selected '{disk}' (model: {model}, size: {size}, type: {connector})".format(
            disk=sdx,
            model=get_hdinfo(sdx, "model"),
            size=get_hdinfo(sdx, "size"),
            connector=get_hdinfo(sdx, "tran")
        )
    )

    erase = settings.get('DEFAULT', 'erase')
    if erase == "yes":
        print("Eraser will start in 10 seconds, ALL DATA WILL BE LOST! Press "
              "Ctrl+C to cancel.")
        try:
            time.sleep(10)
        except KeyboardInterrupt:
            print("Eraser on disk '{0}' cancelled by user!".format(sdx))
            return
        return erase_disk(sdx)
    
    elif erase == "ask":
        confirm = raw_input("Do you want to erase \"{0}\"? [y/N] ".format(sdx))
        if confirm.lower().strip() == "y" or confirm.lower().strip() == "yes":
            return erase_disk(sdx)
    
    print("No disk erased.")

def main(argv=None):
    device = sys.argv[1]
    print do_erasure(device)
    

if __name__ == "__main__":
# checking priveleges
    if os.geteuid() !=  0:
        sys.exit("Must be root to erase data.")

    try:
        arg_var = sys.argv[1]
    except IndexError:
        exit("No devices selected.")

    if len(arg_var) < 7:
        exit("Device not valid.")
        
    # Start
    if os.path.exists(arg_var):
        sys.exit(main(sys.argv))
    else:
        exit("Device does not exit.")

@@ -1,25 +1,25 @@
-#!/usr/bin/env python
+import os%0Aimport stat
 %0Aimp
@@ -33,26 +33,16 @@
 process%0A
-import os%0A
 import t
@@ -49,18 +49,8 @@
 ime%0A
-import sys
 %0Afro
@@ -72,25 +72,24 @@
 rt datetime%0A
-%0A
 from .conf i
@@ -220,16 +220,17 @@
 trip()%0A%0A
+%0A
 def eras
@@ -1148,16 +1148,17 @@
 %0A    %7D%0A%0A
+%0A
 def do_e
@@ -1170,16 +1170,298 @@
 e(sdx):%0A
+    if not os.path.exists(sdx):%0A        raise ValueError(%22Device '%7B0%7D' does not exist.%22.format(sdx))%0A%0A    # check if file is a block special device%0A    if not stat.S_ISBLK(os.stat(sdx).st_mode):%0A        raise ValueError(%22File '%7B0%7D' is not a block special device.%22.format(sdx))%0A    %0A
     prin
@@ -2361,504 +2361,4 @@
 .%22)%0A
-%0Adef main(argv=None):%0A    device = sys.argv%5B1%5D%0A    print do_erasure(device)%0A    %0A%0Aif __name__ == %22__main__%22:%0A# checking priveleges%0A    if os.geteuid() !=  0:%0A        sys.exit(%22Must be root to erase data.%22)%0A%0A    try:%0A        arg_var = sys.argv%5B1%5D%0A    except IndexError:%0A        exit(%22No devices selected.%22)%0A%0A    if len(arg_var) %3C 7:%0A        exit(%22Device not valid.%22)%0A        %0A    # Start%0A    if os.path.exists(arg_var):%0A        sys.exit(main(sys.argv))%0A    else:%0A        exit(%22Device does not exit.%22)%0A

Check if path points a valid device