use std::env;
use std::process::Command;
use std::path::Path;
use std::fs;
fn main() {
let mut binary_path = env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
binary_path.push_str("/target/release/");
let exe_ext = if cfg!(windows) { ".exe" } else { "" };
let binary_name = format!("{}{}", env::var("CARGO_PKG_NAME").unwrap_or("btcli".to_string()), exe_ext);
binary_path.push_str(&binary_name);
if !Path::new(&binary_path).exists() {
eprintln!("Binary file does not exist: {}", binary_path);
return;
}
let original_size = fs::metadata(&binary_path).map(|m| m.len()).unwrap_or(0);
println!("Original binary size: {} bytes", original_size);
let upx_check = Command::new("upx").arg("--version").output();
if upx_check.is_ok() && upx_check.unwrap().status.success() {
println!("Attempting to compress binary with UPX: {}", binary_path);
let upx_output = Command::new("upx")
.args(&["--best", "--lzma", "--force", &binary_path])
.output();
match upx_output {
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
if output.status.success() || stderr.contains("AlreadyPackedException") {
let compressed_size = fs::metadata(&binary_path).map(|m| m.len()).unwrap_or(0);
let reduction = ((original_size as f64 - compressed_size as f64) / original_size as f64 * 100.0).round();
if output.status.success() {
println!("✓ Successfully compressed binary with UPX");
println!(" Size reduced from {} to {} bytes ({:.1}% reduction)",
original_size, compressed_size, reduction);
} else if stderr.contains("AlreadyPackedException") {
println!("⚠ Binary was already UPX compressed");
println!(" Current size: {} bytes", compressed_size);
}
let _ = Command::new("upx").args(&["-q", &binary_path]).status();
} else {
eprintln!("Failed to compress binary with UPX: {}", stderr);
}
}
Err(e) => {
eprintln!("Error executing UPX: {}", e);
}
}
} else {
println!("UPX not found, skipping compression");
}
}