|
| 1 | +use reqwest::get; |
| 2 | +use std::fs::{self, File}; |
| 3 | +use std::path::Path; |
| 4 | + |
| 5 | +async fn download_ubuntu_cloud_image() -> Result<String, Box<dyn std::error::Error>> { |
| 6 | + let url = "https://cloud-images.ubuntu.com/releases/noble/release/ubuntu-24.04-server-cloudimg-amd64.img"; |
| 7 | + |
| 8 | + let dir = Path::new("./vm-data"); |
| 9 | + let file_path = dir.join("ubuntu-24.04-server-cloudimg-amd64.img"); |
| 10 | + |
| 11 | + // 1. Create directory if it doesn't exist |
| 12 | + if !dir.exists() { |
| 13 | + fs::create_dir_all(dir)?; |
| 14 | + println!("Created directory: {:?}", dir); |
| 15 | + } |
| 16 | + |
| 17 | + // 2. Skip if file already exists |
| 18 | + if file_path.exists() { |
| 19 | + println!("Image already exists at {:?}", file_path); |
| 20 | + return Ok(file_path.to_string_lossy().to_string()); |
| 21 | + } |
| 22 | + |
| 23 | + println!("Downloading Ubuntu cloud image..."); |
| 24 | + |
| 25 | + // 3. Download the file |
| 26 | + let mut response = get(url).await?; |
| 27 | + |
| 28 | + if !response.status().is_success() { |
| 29 | + return Err(format!("Download failed: {}", response.status()).into()); |
| 30 | + } |
| 31 | + |
| 32 | + // 4. Create file |
| 33 | + let mut file = File::create(&file_path)?; |
| 34 | + |
| 35 | + // 5. Write response to file |
| 36 | + while let Some(chunk) = response.chunk().await? { |
| 37 | + std::io::copy(&mut chunk.as_ref(), &mut file)?; |
| 38 | + } |
| 39 | + |
| 40 | + println!("Downloaded to {:?}", file_path); |
| 41 | + |
| 42 | + Ok(file_path.to_string_lossy().to_string()) |
| 43 | +} |
| 44 | + |
| 45 | +pub fn initialize() { |
| 46 | + // download image |
| 47 | + let rt = tokio::runtime::Runtime::new().unwrap(); |
| 48 | + match rt.block_on(download_ubuntu_cloud_image()) { |
| 49 | + Ok(path) => println!("Image ready at: {}", path), |
| 50 | + Err(e) => eprintln!("Failed to download image: {}", e), |
| 51 | + } |
| 52 | +} |
0 commit comments