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
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#!/usr/bin/env python3
"""
bootloader.py - Mac OS 15 Sequoia Bootloader 
Uses download URL as bootable USB and JSON as storage disk for installation.
"""

import requests
import duckdb
import json
import hashlib
import os
import shutil
import subprocess
import tempfile
import tarfile
import zipfile
from datetime import datetime
from pathlib import Path
from fastapi import FastAPI, Request, Response, HTTPException, Depends, status
from fastapi.responses import JSONResponse, HTMLResponse, RedirectResponse
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates


app = FastAPI()

class MacOSBootloader:
    def __init__(self, iso_url, storage_json_url):
        self.iso_url = iso_url
        self.storage_json_url = storage_json_url
        self.temp_dir = tempfile.mkdtemp(prefix="macos_sequoia_")
        
        # Bootable USB (download URL) mount point
        self.usb_mount_point = os.path.join(self.temp_dir, "bootable_usb")
        os.makedirs(self.usb_mount_point, exist_ok=True)
        
        # Storage disk (JSON) mount point
        self.storage_mount_point = os.path.join(self.temp_dir, "storage_disk")
        os.makedirs(self.storage_mount_point, exist_ok=True)
        
        # Installation target
        self.install_target = os.path.join(self.temp_dir, "macos_sequoia")
        os.makedirs(self.install_target, exist_ok=True)
        
    def download_bootable_usb(self):
        """Download the bootable USB image (ISO) from URL"""
        print(f"📥 Downloading bootable USB image: {self.iso_url}")
        
        try:
            # Get file info first
            response = requests.head(self.iso_url, allow_redirects=True, timeout=30)
            response.raise_for_status()
            
            file_size = int(response.headers.get('content-length', 0))
            print(f"📦 Bootable USB size: {file_size / (1024*1024*1024):.2f} GB")
            
            # Download the actual file
            usb_path = os.path.join(self.temp_dir, "bootable_usb_image.iso")
            
            print("⏬ Downloading installation media...")
            with requests.get(self.iso_url, stream=True, timeout=60) as r:
                r.raise_for_status()
                with open(usb_path, 'wb') as f:
                    for chunk in r.iter_content(chunk_size=8192):
                        f.write(chunk)
                        downloaded = os.path.getsize(usb_path)
                        progress = (downloaded / file_size) * 100
                        print(f"   📊 Progress: {progress:.1f}%", end='\r')
            
            print(f"\n✅ Bootable USB downloaded: {usb_path}")
            return usb_path
            
        except Exception as e:
            print(f"❌ Bootable USB download error: {e}")
            return None
    
    def mount_bootable_usb(self, usb_path):
        """Mount the bootable USB image"""
        print("🔗 Mounting bootable USB...")
        
        try:
            # For ISO files, we need to extract or mount them
            if usb_path.endswith('.iso'):
                # Try to mount using system commands (Linux/Mac)
                try:
                    subprocess.run([
                        'hdiutil', 'attach', usb_path, 
                        '-mountpoint', self.usb_mount_point,
                        '-noverify', '-nobrowse'
                    ], check=True, capture_output=True)
                    print("✅ Bootable USB mounted using hdiutil")
                except:
                    # Fallback: extract using Python
                    print("⚠️  Using fallback extraction method")
                    with open(usb_path, 'rb') as iso_file:
                        # Simple extraction - actual ISO parsing would be more complex
                        # This is a simplified version for demonstration
                        shutil.copyfileobj(iso_file, open(os.path.join(self.usb_mount_point, 'boot.image'), 'wb'))
            
            elif usb_path.endswith(('.zip', '.tar.gz', '.tgz')):
                # Extract compressed files
                if usb_path.endswith('.zip'):
                    with zipfile.ZipFile(usb_path, 'r') as zip_ref:
                        zip_ref.extractall(self.usb_mount_point)
                else:
                    with tarfile.open(usb_path, 'r:*') as tar_ref:
                        tar_ref.extractall(self.usb_mount_point)
                
                print("✅ Bootable USB extracted")
            
            # Verify USB contents
            usb_contents = os.listdir(self.usb_mount_point)
            print(f"📁 USB contents: {len(usb_contents)} items")
            
            return True
            
        except Exception as e:
            print(f"❌ Bootable USB mount error: {e}")
            return False
    
    def connect_to_storage_disk(self):
        """Connect to JSON storage disk"""
        print(f"💾 Connecting to storage disk: {self.storage_json_url}")
        
        try:
            # Download storage JSON
            response = requests.get(self.storage_json_url, timeout=30)
            response.raise_for_status()
            self.storage_data = response.json()
            
            # Create storage disk structure
            storage_structure = self.storage_data.get('storage_structure', {})
            self._create_storage_structure(self.storage_mount_point, storage_structure)
            
            print(f"✅ Storage disk connected: {len(storage_structure)} directories")
            return True
            
        except Exception as e:
            print(f"❌ Storage disk connection error: {e}")
            return False
    
    def _create_storage_structure(self, base_path, structure):
        """Create storage disk directory structure"""
        for dir_name, dir_content in structure.items():
            dir_path = os.path.join(base_path, dir_name)
            os.makedirs(dir_path, exist_ok=True)
            
            if isinstance(dir_content, dict):
                self._create_storage_structure(dir_path, dir_content)
    
    def verify_installation_media(self):
        """Verify the bootable USB contents"""
        print("🔍 Verifying installation media...")
        
        try:
            required_files = [
                'boot.efi', 'mach_kernel', 'BaseSystem.dmg',
                'InstallESD.dmg', 'InstallInfo.plist'
            ]
            
            usb_files = os.listdir(self.usb_mount_point)
            found_files = [f for f in required_files if any(f in usb_file for usb_file in usb_files)]
            
            print(f"✅ Found {len(found_files)}/{len(required_files)} required files")
            return len(found_files) >= 3  # At least 3 critical files
            
        except Exception as e:
            print(f"❌ Media verification error: {e}")
            return False
    
    def prepare_installation(self):
        """Prepare the installation environment"""
        print("🛠️ Preparing installation environment...")
        
        try:
            # Create installation directories
            directories = [
                'System', 'Library', 'Applications', 'Users', 
                'private', 'var', 'tmp', 'Volumes'
            ]
            
            for directory in directories:
                os.makedirs(os.path.join(self.install_target, directory), exist_ok=True)
            
            # Copy essential files from USB to installation target
            essential_files = ['mach_kernel', 'boot.efi']
            for file in essential_files:
                src = self._find_file_in_usb(file)
                if src:
                    dst = os.path.join(self.install_target, file)
                    shutil.copy2(src, dst)
                    print(f"   ✅ Copied: {file}")
            
            return True
            
        except Exception as e:
            print(f"❌ Preparation error: {e}")
            return False
    
    def _find_file_in_usb(self, filename):
        """Find a file in the USB mount point"""
        for root, dirs, files in os.walk(self.usb_mount_point):
            if filename in files:
                return os.path.join(root, filename)
        return None
    
    def install_operating_system(self):
        """Main installation process"""
        print("🚀 Installing Mac OS 15 Sequoia...")
        
        try:
            # Step 1: Install base system
            print("📦 Installing base system...")
            base_system = self._find_file_in_usb('BaseSystem.dmg')
            if base_system:
                self._install_dmg(base_system, self.install_target)
            
            # Step 2: Install additional components
            print("⚙️ Installing system components...")
            install_esd = self._find_file_in_usb('InstallESD.dmg')
            if install_esd:
                self._install_dmg(install_esd, os.path.join(self.install_target, 'System', 'Installation'))
            
            # Step 3: Copy installation packages
            print("📦 Copying installation packages...")
            pkg_dir = os.path.join(self.usb_mount_point, 'Packages')
            if os.path.exists(pkg_dir):
                target_pkg = os.path.join(self.install_target, 'System', 'Installation', 'Packages')
                shutil.copytree(pkg_dir, target_pkg)
                print(f"   ✅ Copied {len(os.listdir(pkg_dir))} packages")
            
            # Step 4: Create system configuration
            print("⚙️ Creating system configuration...")
            self._create_system_configuration()
            
            # Step 5: Set up boot files
            print("👢 Setting up boot configuration...")
            self._setup_boot_configuration()
            
            print("✅ Operating system installation complete")
            return True
            
        except Exception as e:
            print(f"❌ Installation error: {e}")
            return False
    
    def _install_dmg(self, dmg_path, target_dir):
        """Simulate DMG installation"""
        print(f"   🖥️ Installing {os.path.basename(dmg_path)}...")
        
        # In a real scenario, this would use hdiutil or similar
        # For simulation, we'll create the expected directory structure
        os.makedirs(target_dir, exist_ok=True)
        
        # Create essential files that would be in the DMG
        essential_files = [
            'System/Library/CoreServices/SystemVersion.plist',
            'System/Library/CoreServices/boot.efi',
            'usr/lib/dyld',
            'bin/bash',
            'sbin/launchd'
        ]
        
        for file_path in essential_files:
            full_path = os.path.join(target_dir, file_path)
            os.makedirs(os.path.dirname(full_path), exist_ok=True)
            
            if file_path.endswith('.plist'):
                # Create plist file
                plist_content = {
                    'ProductName': 'Mac OS X',
                    'ProductVersion': '15.0',
                    'ProductBuildVersion': '24A344',
                    'ProductCopyright': '1983-2024 Apple Inc.'
                }
                with open(full_path, 'w') as f:
                    json.dump(plist_content, f, indent=2)
            else:
                # Create placeholder file
                with open(full_path, 'w') as f:
                    f.write(f"# Placeholder for {os.path.basename(file_path)}\n")
        
        print(f"   ✅ Installed {os.path.basename(dmg_path)}")
    
    def _create_system_configuration(self):
        """Create system configuration files"""
        config_files = {
            'System/Library/CoreServices/SystemVersion.plist': {
                'ProductName': 'Mac OS X',
                'ProductVersion': '15.0',
                'ProductBuildVersion': '24A344',
                'ProductCopyright': '1983-2024 Apple Inc.'
            },
            'etc/hosts': '127.0.0.1 localhost\n::1 localhost\n',
            'etc/fstab': ''  # Empty fstab for now
        }
        
        for file_path, content in config_files.items():
            full_path = os.path.join(self.install_target, file_path)
            os.makedirs(os.path.dirname(full_path), exist_ok=True)
            
            if isinstance(content, dict):
                with open(full_path, 'w') as f:
                    json.dump(content, f, indent=2)
            else:
                with open(full_path, 'w') as f:
                    f.write(content)
    
    def _setup_boot_configuration(self):
        """Set up boot configuration"""
        boot_files = {
            'boot.efi': '# UEFI bootloader\n',
            'System/Library/CoreServices/boot.efi': '# macOS bootloader\n',
            'Library/Preferences/SystemConfiguration/com.apple.Boot.plist': {
                'Kernel Flags': '',
                'Kernel Cache': 'prelinkedkernel',
                'Timeout': '0'
            }
        }
        
        for file_path, content in boot_files.items():
            full_path = os.path.join(self.install_target, file_path)
            os.makedirs(os.path.dirname(full_path), exist_ok=True)
            
            if isinstance(content, dict):
                with open(full_path, 'w') as f:
                    json.dump(content, f, indent=2)
            else:
                with open(full_path, 'w') as f:
                    f.write(content)
    
    def finalize_installation(self):
        """Finalize the installation"""
        print("🎯 Finalizing installation...")
        
        try:
            # Update storage disk with installation info
            installation_info = {
                'installation_date': datetime.utcnow().isoformat(),
                'version': '15.0',
                'build': '24A344',
                'install_path': self.install_target,
                'status': 'completed'
            }
            
            info_path = os.path.join(self.storage_mount_point, 'installation_info.json')
            with open(info_path, 'w') as f:
                json.dump(installation_info, f, indent=2)
            
            # Create success marker
            success_path = os.path.join(self.install_target, '.installation_complete')
            with open(success_path, 'w') as f:
                f.write('Installation completed successfully\n')
            
            print("✅ Installation finalized")
            return True
            
        except Exception as e:
            print(f"❌ Finalization error: {e}")
            return False
    
    def verify_installation(self):
        """Verify the installation was successful"""
        print("🔍 Verifying installation...")
        
        try:
            required_files = [
                'mach_kernel',
                'System/Library/CoreServices/SystemVersion.plist',
                'System/Library/CoreServices/boot.efi',
                'usr/lib/dyld'
            ]
            
            missing_files = []
            for file_path in required_files:
                full_path = os.path.join(self.install_target, file_path)
                if not os.path.exists(full_path):
                    missing_files.append(file_path)
            
            if missing_files:
                print(f"❌ Missing files: {missing_files}")
                return False
            
            print("✅ Installation verification passed")
            return True
            
        except Exception as e:
            print(f"❌ Verification error: {e}")
            return False
    
    def run_installation(self):
        """Main installation process"""
        print("🚀 Starting Mac OS 15 Sequoia Installation")
        print("=" * 60)
        print(f"📀 Bootable USB: {self.iso_url}")
        print(f"💾 Storage Disk: {self.storage_json_url}")
        print("=" * 60)
        
        # Step 1: Download bootable USB
        usb_path = self.download_bootable_usb()
        if not usb_path:
            return False
        
        # Step 2: Mount bootable USB
        if not self.mount_bootable_usb(usb_path):
            return False
        
        # Step 3: Connect to storage disk
        if not self.connect_to_storage_disk():
            return False
        
        # Step 4: Verify installation media
        if not self.verify_installation_media():
            return False
        
        # Step 5: Prepare installation
        if not self.prepare_installation():
            return False
        
        # Step 6: Install OS
        if not self.install_operating_system():
            return False
        
        # Step 7: Finalize installation
        if not self.finalize_installation():
            return False
        
        # Step 8: Verify installation
        if not self.verify_installation():
            return False
        
        print("=" * 60)
        print("🎉 Mac OS 15 Sequoia Installation Complete!")
        print(f"📁 Installed at: {self.install_target}")
        print(f"💾 Storage updated: {self.storage_mount_point}")
        
        return True
    
    def cleanup(self):
        """Clean up temporary files"""
        try:
            shutil.rmtree(self.temp_dir)
            print(f"🧹 Cleaned up temporary files: {self.temp_dir}")
        except:
            print(f"⚠️ Could not clean up temporary files: {self.temp_dir}")

def main():
    # Configuration
    ISO_URL = "https://archive.org/download/mac-os-15-sequoia-by-metaperso/Mac%20Os%2015%20Sequoia%20by%20Metaperso.iso"
    STORAGE_JSON_URL = "https://huggingface.co/datasets/Fred808/helium/raw/main/storage.json"
    
    # Create bootloader instance
    bootloader = MacOSBootloader(ISO_URL, STORAGE_JSON_URL)
    
    try:
        # Run installation
        success = bootloader.run_installation()
        
        if success:
            print("\n✅ Mac OS 15 Sequoia installed successfully!")
            print(f"📂 OS Location: {bootloader.install_target}")
        else:
            print("\n❌ Installation failed!")
            return 1
            
    except KeyboardInterrupt:
        print("\n⏹️ Installation interrupted by user")
        return 1
    except Exception as e:
        print(f"\n💥 Unexpected error: {e}")
        return 1
    finally:
        # Ask user if they want to clean up
        cleanup = input("\n🧹 Clean up installation files? (y/N): ").lower().strip()
        if cleanup == 'y':
            bootloader.cleanup()
        else:
            print(f"📁 Installation files preserved at: {bootloader.temp_dir}")
    
    return 0

if __name__ == "__main__":
    exit(main())
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)