import os
import time
import subprocess
import json
import getpass

# --- 1. ADMIN AUTHENTICATION ---
MASTER_USER = "admin"
MASTER_PASS = "Cipher123!"  # Change this to whatever you want!

print("========================================")
print("  🛡️ CipherWipe Offline Master Tool     ")
print("========================================\n")

# Security Check Loop
authenticated = False
for attempt in range(3):
    user_input = input("Username: ").strip()
    pass_input = getpass.getpass("Password: ") # Hides the typing!
    
    if user_input == MASTER_USER and pass_input == MASTER_PASS:
        print("\n[+] ACCESS GRANTED. Welcome, Administrator.\n")
        authenticated = True
        break
    else:
        print(f"[-] ACCESS DENIED. ({2 - attempt} attempts remaining)\n")

if not authenticated:
    print("SYSTEM LOCKOUT. Exiting...")
    time.sleep(3)
    exit()

# --- 2. HARDWARE DETECTION ---
def get_usb_drives():
    print("[*] Scanning system for removable media...")
    drives = []
    try:
        cmd = 'powershell -NoProfile -Command "Get-CimInstance Win32_LogicalDisk | Where-Object { $_.DriveType -eq 2 } | Select-Object DeviceID, VolumeName, Size | ConvertTo-Json"'
        result = subprocess.check_output(cmd, shell=True).decode().strip()
        
        if not result:
            return drives
            
        data = json.loads(result)
        # Handle single object vs list of objects
        if isinstance(data, dict):
            data = [data]
            
        for d in data:
            if d.get('Size'):
                cap_gb = round(int(d['Size']) / 1073741824, 2)
                drives.append({
                    'letter': d['DeviceID'],
                    'name': d.get('VolumeName', 'USB Drive'),
                    'size': cap_gb
                })
    except Exception as e:
        print(f"Error scanning drives: {e}")
    return drives

available_drives = get_usb_drives()

if not available_drives:
    print("[-] No USB drives detected on this system.")
    input("Press Enter to exit...")
    exit()

# --- 3. THE MENU INTERFACE ---
print("\nAVAILABLE TARGETS:")
for i, drive in enumerate(available_drives):
    print(f"  [{i+1}] {drive['letter']} - {drive['name']} ({drive['size']} GB)")

try:
    choice = int(input("\nSelect target number to wipe (or 0 to cancel): "))
    if choice == 0:
        exit()
    target_drive = available_drives[choice-1]
except (ValueError, IndexError):
    print("[-] Invalid selection. Exiting.")
    time.sleep(2)
    exit()

print("\nSECURITY ALGORITHMS:")
print("  [1] Fast Zero-Fill (1 Pass)")
print("  [2] DoD 5220.22-M (3 Passes)")
print("  [3] Gutmann Method (35 Passes)")
try:
    algo_choice = int(input("Select algorithm: "))
    passes = 1
    if algo_choice == 2: passes = 3
    elif algo_choice == 3: passes = 35
except ValueError:
    print("[-] Invalid selection. Exiting.")
    exit()

# --- 4. THE WIPE ENGINE (Standalone version) ---
print(f"\n[!] WARNING: YOU ARE ABOUT TO DESTROY ALL DATA ON {target_drive['letter']}")
confirm = input("Type 'DESTROY' to proceed: ")

if confirm != "DESTROY":
    print("Aborted.")
    exit()

letter = target_drive['letter'][0]
temp_file = f"{letter}:\\cipherwipe_secure_erase.tmp"
chunk_size = 1024 * 1024 * 4  
exact_drive_size = int(target_drive['size'] * 1073741824)

print(f"\n[!] STEP 1: Quick Formatting {target_drive['letter']}...")
try:
    subprocess.run(f'powershell -NoProfile -Command "Format-Volume -DriveLetter {letter} -Confirm:$false"', shell=True)
except:
    pass

print(f"[!] STEP 2: Executing {passes}-Pass Secure Wipe...")
try:
    with open(temp_file, 'wb') as f:
        for current_pass in range(1, passes + 1):
            f.seek(0) 
            bytes_written = 0
            last_percent = 0
            
            chunk = b'\x00' * chunk_size if current_pass % 2 != 0 else b'\xFF' * chunk_size

            while True:
                try:
                    f.write(chunk)
                    bytes_written += chunk_size
                    
                    if exact_drive_size > 0:
                        percent = int((bytes_written / exact_drive_size) * 100)
                        if percent >= last_percent + 5:
                            print(f"    -> Pass {current_pass}/{passes} | Drive Progress: {min(percent, 99)}%")
                            last_percent = percent
                            
                    if current_pass > 1 and bytes_written >= exact_drive_size:
                        break

                except OSError:
                    exact_drive_size = bytes_written # Disk full
                    break
                    
    print("\n[+] WIPE COMPLETED SUCCESSFULLY.")
except Exception as e:
    print(f"\n[-] WIPE FAILED: {e}")
finally:
    if os.path.exists(temp_file):
        try: os.remove(temp_file)
        except: pass

input("\nPress Enter to exit...")