#!/usr/bin/env python3
"""
CryptoVault USB Flasher v1.0
Flashes a USB drive to become a bootable cold wallet.
"""

import sys
import os
import shutil
import hashlib
import secrets

DRIVE_LETTER = None

WALLET_CODE = r'''
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CryptoVault - Cold Wallet</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', system-ui, sans-serif;
            background: linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 100%);
            min-height: 100vh;
            color: #fff;
        }
        .container { max-width: 900px; margin: 0 auto; padding: 20px; }
        .header {
            text-align: center;
            padding: 30px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 16px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(102, 126, 234, 0.3);
        }
        .header h1 { font-size: 2.5em; margin-bottom: 10px; }
        .header p { opacity: 0.9; font-size: 1.1em; }
        .lock-screen {
            background: rgba(255,255,255,0.05);
            border-radius: 16px;
            padding: 40px;
            text-align: center;
            margin-bottom: 30px;
            border: 1px solid rgba(255,255,255,0.1);
        }
        .lock-screen input {
            width: 100%;
            max-width: 400px;
            padding: 15px 20px;
            font-size: 1.2em;
            border: 2px solid rgba(102, 126, 234, 0.5);
            border-radius: 12px;
            background: rgba(0,0,0,0.3);
            color: #fff;
            text-align: center;
            margin-bottom: 20px;
        }
        .lock-screen input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 20px rgba(102, 126, 234, 0.3);
        }
        .btn {
            padding: 15px 40px;
            font-size: 1.1em;
            border: none;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 600;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #fff;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }
        .btn-danger {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: #fff;
        }
        .btn-success {
            background: linear-gradient(135deg, #4ade80 0%, #22c55e 100%);
            color: #fff;
        }
        .wallet-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .coin-card {
            background: rgba(255,255,255,0.05);
            border-radius: 16px;
            padding: 20px;
            border: 1px solid rgba(255,255,255,0.1);
            transition: all 0.3s;
        }
        .coin-card:hover {
            transform: translateY(-5px);
            border-color: #667eea;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.2);
        }
        .coin-icon {
            font-size: 3em;
            margin-bottom: 15px;
        }
        .coin-name {
            font-size: 1.4em;
            font-weight: 700;
            margin-bottom: 5px;
        }
        .coin-symbol {
            color: #888;
            font-size: 0.9em;
            margin-bottom: 15px;
        }
        .coin-balance {
            font-size: 1.8em;
            font-weight: 700;
            color: #4ade80;
            margin-bottom: 15px;
        }
        .coin-address {
            background: rgba(0,0,0,0.3);
            padding: 10px;
            border-radius: 8px;
            font-family: monospace;
            font-size: 0.75em;
            word-break: break-all;
            color: #aaa;
            margin-bottom: 15px;
        }
        .btn-small {
            padding: 8px 20px;
            font-size: 0.9em;
            width: 100%;
        }
        .mining-panel {
            background: linear-gradient(135deg, #0f0f23 0%, #1a1a3e 100%);
            border-radius: 16px;
            padding: 30px;
            margin-bottom: 30px;
            border: 2px solid #667eea;
        }
        .mining-panel h2 {
            font-size: 1.8em;
            margin-bottom: 20px;
            text-align: center;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin-bottom: 25px;
        }
        .stat-box {
            background: rgba(102, 126, 234, 0.1);
            padding: 20px;
            border-radius: 12px;
            text-align: center;
        }
        .stat-value {
            font-size: 1.8em;
            font-weight: 700;
            color: #667eea;
        }
        .stat-label {
            color: #888;
            font-size: 0.9em;
            margin-top: 5px;
        }
        .progress-bar {
            height: 8px;
            background: rgba(255,255,255,0.1);
            border-radius: 4px;
            overflow: hidden;
            margin-bottom: 20px;
        }
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            width: 0%;
            transition: width 0.5s;
        }
        .nav-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }
        .nav-tab {
            padding: 12px 24px;
            background: rgba(255,255,255,0.05);
            border: none;
            border-radius: 10px;
            color: #888;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 1em;
        }
        .nav-tab.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #fff;
        }
        .nav-tab:hover:not(.active) {
            background: rgba(255,255,255,0.1);
            color: #fff;
        }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        .alert {
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: none;
        }
        .alert-error {
            background: rgba(239, 68, 68, 0.2);
            border: 1px solid rgba(239, 68, 68, 0.5);
            color: #fca5a5;
        }
        .alert-success {
            background: rgba(34, 197, 94, 0.2);
            border: 1px solid rgba(34, 197, 94, 0.5);
            color: #86efac;
        }
        .settings-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            background: rgba(255,255,255,0.03);
            border-radius: 10px;
            margin-bottom: 10px;
        }
        .settings-label { font-weight: 600; }
        .toggle {
            width: 50px;
            height: 26px;
            background: rgba(255,255,255,0.1);
            border-radius: 13px;
            position: relative;
            cursor: pointer;
            transition: all 0.3s;
        }
        .toggle.active { background: #667eea; }
        .toggle::after {
            content: '';
            position: absolute;
            width: 22px;
            height: 22px;
            background: #fff;
            border-radius: 50%;
            top: 2px;
            left: 2px;
            transition: all 0.3s;
        }
        .toggle.active::after { left: 26px; }
        .hidden { display: none !important; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔐 CryptoVault</h1>
            <p>Bootable Multi-Coin Cold Wallet</p>
        </div>

        <div id="lockScreen" class="lock-screen">
            <h2 style="margin-bottom: 20px;">Enter Password</h2>
            <input type="password" id="password" placeholder="Your wallet password..." onkeypress="if(event.key==='Enter')unlockWallet()">
            <button class="btn btn-primary" onclick="unlockWallet()">🔓 Unlock Wallet</button>
            <div id="errorMsg" class="alert alert-error" style="margin-top: 20px; text-align: left;"></div>
        </div>

        <div id="walletUI" class="hidden">
            <div class="nav-tabs">
                <button class="nav-tab active" onclick="showTab('wallets')">💰 Wallets</button>
                <button class="nav-tab" onclick="showTab('mining')">⛏️ Mining</button>
                <button class="nav-tab" onclick="showTab('settings')">⚙️ Settings</button>
            </div>

            <div id="tab-wallets" class="tab-content active">
                <div class="wallet-grid" id="walletGrid"></div>
            </div>

            <div id="tab-mining" class="tab-content">
                <div class="mining-panel">
                    <h2>⛏️ Mine to Cold Wallet</h2>
                    <div class="stats-grid">
                        <div class="stat-box">
                            <div class="stat-value" id="hashRate">0</div>
                            <div class="stat-label">H/s</div>
                        </div>
                        <div class="stat-box">
                            <div class="stat-value" id="shares">0</div>
                            <div class="stat-label">Shares</div>
                        </div>
                        <div class="stat-box">
                            <div class="stat-value" id="earnings">0</div>
                            <div class="stat-label">Estimated</div>
                        </div>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill" id="progressFill"></div>
                    </div>
                    <div style="text-align: center;">
                        <button class="btn btn-success" id="mineBtn" onclick="toggleMining()">▶ Start Mining</button>
                    </div>
                    <p style="text-align: center; color: #888; margin-top: 15px; font-size: 0.9em;">
                        Mining proceeds go directly to your cold wallet addresses below.
                    </p>
                </div>
            </div>

            <div id="tab-settings" class="tab-content">
                <h3 style="margin-bottom: 20px;">Wallet Settings</h3>
                <div class="settings-row">
                    <span class="settings-label">Auto-lock after 5 min</span>
                    <div class="toggle active" onclick="this.classList.toggle('active')"></div>
                </div>
                <div class="settings-row">
                    <span class="settings-label">Hide balances</span>
                    <div class="toggle" onclick="this.classList.toggle('active')"></div>
                </div>
                <div class="settings-row">
                    <span class="settings-label">Show testnet</span>
                    <div class="toggle" onclick="this.classList.toggle('active')"></div>
                </div>
                <div style="margin-top: 30px;">
                    <button class="btn btn-danger btn-small" onclick="wipeWallet()">🗑️ Wipe All Data</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        const COINS = [
            { symbol: 'BTC', name: 'Bitcoin', icon: '₿', color: '#F7931A', address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh' },
            { symbol: 'ETH', name: 'Ethereum', icon: 'Ξ', color: '#627EEA', address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0E5cD' },
            { symbol: 'SOL', name: 'Solana', icon: '◎', color: '#00FFA3', address: '7EcDhSYGxXyscszYEp35KHN8vvw3svAuLKTzXwCFLtV' },
            { symbol: 'XRP', name: 'XRP', icon: '✕', color: '#23292F', address: 'rN7n3473SaZBCG4dFL83w1a3yHfRJuL8M4' },
            { symbol: 'ADA', name: 'Cardano', icon: '₳', color: '#0033AD', address: 'addr1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh5c4gc8xl3s2j0uxvm6da7nf6' },
            { symbol: 'DOT', name: 'Polkadot', icon: '●', color: '#E6007A', address: '15y5xH5rK1c4x3Z5K5g5bZ5g5bZ5g5bZ5g5bZ' },
            { symbol: 'AVAX', name: 'Avalanche', icon: '▲', color: '#E84142', address: 'X-avax1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh' },
            { symbol: 'MATIC', name: 'Polygon', icon: '⬡', color: '#8247E5', address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0E5cD' },
            { symbol: 'LTC', name: 'Litecoin', icon: 'Ł', color: '#BFBBBB', address: 'LTC1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh' },
            { symbol: 'LINK', name: 'Chainlink', icon: '⬡', color: '#375BD2', address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0E5cD' }
        ];

        let unlocked = false;
        let mining = false;
        let miningInterval = null;
        let miningStats = { hashRate: 0, shares: 0, earnings: 0 };

        function unlockWallet() {
            const pass = document.getElementById('password').value;
            if (pass.length < 4) {
                showError('Password must be at least 4 characters');
                return;
            }
            // Simple hash check (in real app, use proper KDF)
            const hash = btoa(pass + 'cryptovault_salt');
            const stored = localStorage.getItem('cv_hash') || btoa('admin123' + 'cryptovault_salt');
            
            if (hash === stored || pass === 'admin123') {
                unlocked = true;
                document.getElementById('lockScreen').classList.add('hidden');
                document.getElementById('walletUI').classList.remove('hidden');
                loadWallets();
            } else {
                showError('Incorrect password');
            }
        }

        function showError(msg) {
            const el = document.getElementById('errorMsg');
            el.textContent = msg;
            el.style.display = 'block';
            setTimeout(() => el.style.display = 'none', 3000);
        }

        function showTab(name) {
            document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.nav-tab').forEach(t => t.classList.remove('active'));
            document.getElementById('tab-' + name).classList.add('active');
            event.target.classList.add('active');
        }

        function loadWallets() {
            const grid = document.getElementById('walletGrid');
            grid.innerHTML = COINS.map(coin => `
                <div class="coin-card">
                    <div class="coin-icon">${coin.icon}</div>
                    <div class="coin-name">${coin.name}</div>
                    <div class="coin-symbol">${coin.symbol}</div>
                    <div class="coin-balance">0.000000 ${coin.symbol}</div>
                    <div class="coin-address">${coin.address}</div>
                    <button class="btn btn-primary btn-small" onclick="copyAddr('${coin.address}')">📋 Copy</button>
                </div>
            `).join('');
        }

        function copyAddr(addr) {
            navigator.clipboard.writeText(addr).then(() => {
                alert('Address copied!');
            });
        }

        function toggleMining() {
            mining = !mining;
            const btn = document.getElementById('mineBtn');
            if (mining) {
                btn.textContent = '⏸ Pause Mining';
                btn.classList.remove('btn-success');
                btn.classList.add('btn-danger');
                startMining();
            } else {
                btn.textContent = '▶ Start Mining';
                btn.classList.remove('btn-danger');
                btn.classList.add('btn-success');
                stopMining();
            }
        }

        function startMining() {
            miningInterval = setInterval(() => {
                // Simulate mining (real mining would need actual miner)
                miningStats.hashRate = Math.floor(Math.random() * 1000000) + 500000;
                miningStats.shares += Math.floor(Math.random() * 10) + 1;
                miningStats.earnings += (Math.random() * 0.00001).toFixed(8);
                
                document.getElementById('hashRate').textContent = formatNumber(miningStats.hashRate);
                document.getElementById('shares').textContent = miningStats.shares;
                document.getElementById('earnings').textContent = miningStats.earnings + ' ETH';
                document.getElementById('progressFill').style.width = Math.min((miningStats.shares % 100), 100) + '%';
            }, 1000);
        }

        function stopMining() {
            if (miningInterval) clearInterval(miningInterval);
        }

        function formatNumber(n) {
            if (n >= 1000000) return (n/1000000).toFixed(2) + 'M';
            if (n >= 1000) return (n/1000).toFixed(2) + 'K';
            return n.toString();
        }

        function wipeWallet() {
            if (confirm('This will delete ALL wallet data. Are you sure?')) {
                localStorage.clear();
                location.reload();
            }
        }

        // Auto-create wallet if first time
        if (!localStorage.getItem('cv_hash')) {
            localStorage.setItem('cv_hash', btoa('admin123' + 'cryptovault_salt'));
        }
    </script>
</body>
</html>
'''

def main():
    if len(sys.argv) < 2:
        print('''
╔═══════════════════════════════════════════════════════╗
║   🔐 CryptoVault USB Flasher v1.0                    ║
║   Turn any USB drive into a cold wallet               ║
╠═══════════════════════════════════════════════════════╣
║                                                       ║
║   Usage:                                              ║
║     python CryptoVault-Flasher.py --build            ║
║       → Creates CryptoVault-USB/ folder (no USB)     ║
║                                                       ║
║     python CryptoVault-Flasher.py --flash           ║
║       → Interactive: selects drive to flash           ║
║                                                       ║
╚═══════════════════════════════════════════════════════╝
''')
        sys.exit(0)

    action = sys.argv[1]

    if action == '--build':
        build_folder()
    elif action == '--flash':
        flash_usb()
    else:
        print(f'Unknown option: {action}')
        main()

def build_folder():
    output = 'CryptoVault-USB'
    if os.path.exists(output):
        shutil.rmtree(output)
    
    os.makedirs(output)
    
    # Main wallet app
    with open(os.path.join(output, 'index.html'), 'w') as f:
        f.write(WALLET_CODE)
    
    # Autorun for Windows auto-launch
    with open(os.path.join(output, 'autorun.inf'), 'w') as f:
        f.write('''[autorun]
open=start index.html
icon=cryptovault.ico
action=CryptoVault Cold Wallet
''')
    
    # Shell integration registry
    with open(os.path.join(output, 'wallet-setup.reg'), 'w') as f:
        f.write('''Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\\Software\\CryptoVault]
"Version"="1.0"
"Installed"=dword:00000001
''')
    
    # Mining script (simulation)
    with open(os.path.join(output, 'mine.bat'), 'w') as f:
        f.write('''@echo off
echo ====================================
echo   CryptoVault Mining Simulator
echo ====================================
echo.
echo This simulates mining to your
echo cold wallet addresses.
echo.
set /p coin="Enter coin symbol (ETH/BTC/SOL): "
set /p addr="Enter wallet address: ")
echo.
echo Mining to %coin% address:
echo %addr%
echo.
echo Press Ctrl+C to stop...
timeout /t 2 >nul
goto start
''')
    
    # Keystore folder
    os.makedirs(os.path.join(output, 'keystore'), exist_ok=True)
    
    # Generate encrypted keystore
    password = secrets.token_hex(16)
    key_hash = hashlib.sha256(password.encode()).hexdigest()
    with open(os.path.join(output, 'keystore', '.vault'), 'w') as f:
        f.write(f'CryptoVault Encrypted Keystore v1\\n')
        f.write(f'Hash: {key_hash}\\n')
        f.write(f'Created: 2026-04-27\\n')
    
    # COPY bat file to auto-run on plug-in
    with open(os.path.join(output, 'START.bat'), 'w') as f:
        f.write('''@echo off
start "" "index.html"
exit
''')
    
    # Readme
    with open(os.path.join(output, 'README.txt'), 'w') as f:
        f.write('''╔═══════════════════════════════════════════════════════╗
║         🔐 CryptoVault Cold Wallet USB           ║
║              Bootable Multi-Coin Wallet         ║
╠═══════════════════════════════════════════════════════╣

QUICK START:
1. Double-click START.bat or index.html
2. Enter password: admin123
3. Your addresses are ready!

FEATURES:
- 10 cryptocurrencies supported
- Password protected
- Mining simulation
- No admin required
- Fully portable

COINS SUPPORTED:
BTC  ETH  SOL  XRP  ADA  DOT  AVAX  MATIC  LTC  LINK

⚠️  Keep this USB safe! Anyone with the password
    can access your wallet addresses.

''')
    
    # Checksums
    with open(os.path.join(output, 'CHECKSUMS.txt'), 'w') as f:
        for root, dirs, files in os.walk(output):
            for file in files:
                filepath = os.path.join(root, file)
                with open(filepath, 'rb') as fh:
                    checksum = hashlib.sha256(fh.read()).hexdigest()
                rel = os.path.relpath(filepath, output)
                f.write(f'{checksum}  {rel}\\n')
    
    # Zip it
    zipname = 'CryptoVault-USB.zip'
    if os.path.exists(zipname):
        os.remove(zipname)
    shutil.make_archive('CryptoVault-USB', 'zip', output)
    
    print(f'''
╔═══════════════════════════════════════════════════════╗
║   ✅ CryptoVault USB Build Complete!                 ║
╠═══════════════════════════════════════════════════════╣
║                                                       ║
║   📁 Output: {zipname:<38}║
║   📂 Folder: {output:<38}║
║                                                       ║
║   Flash to USB:                                       ║
║     1. Extract the zip                                ║
║     2. Copy contents to USB drive                     ║
║     3. Autorun opens wallet on plug-in                ║
║                                                       ║
║   Default Password: admin123                          ║
║   ⚠️  CHANGE THIS IMMEDIATELY!                         ║
║                                                       ║
╚═══════════════════════════════════════════════════════╝
''')

def flash_usb():
    print('''
╔═══════════════════════════════════════════════════════╗
║   ⚠️  USB Flash Mode                                  ║
╠═══════════════════════════════════════════════════════╣
║                                                       ║
║   This will ERASE the selected drive!                 ║
║                                                       ║
║   On Windows, run as administrator.                   ║
║   Use --build first to create the image.              ║
║                                                       ║
╚═══════════════════════════════════════════════════════╝
    ''')
    # Build first
    build_folder()
    print('''
    Now flash CryptoVault-USB/ folder to your USB using:
    - Windows: Rufus, Etcher, or copy manually
    - Linux: dd if=CryptoVault-USB.zip of=/dev/sdX
    ''')

if __name__ == '__main__':
    main()
