1use crate::error::{EncryptError, Result};
2use crate::vault::Vault;
3use clap::{Parser, Subcommand};
4use colored::*;
5use indicatif::{ProgressBar, ProgressStyle};
6use std::process;
7
8#[derive(Parser)]
9#[command(name = "encrypt")]
10#[command(about = "A top-level secrets orchestrator. Not just another .env tool — this one encrypts, locks, and sets you up for secure local and team dev.")]
11#[command(version = crate::get_version())]
12pub struct Cli {
13 #[command(subcommand)]
14 pub command: Commands,
15}
16
17#[derive(Subcommand)]
18pub enum Commands {
19 Init,
21 Lockup {
23 password: String,
24 },
25 Setup {
27 password: String,
28 },
29 Set {
31 key_value: String,
32 },
33 Get {
35 key: String,
36 },
37 Unlock,
39 Status,
41 Reset,
43}
44
45pub fn run() {
46 let cli = Cli::parse();
47
48 let result = match cli.command {
49 Commands::Init => init_command(),
50 Commands::Lockup { password } => lockup_command(&password),
51 Commands::Setup { password } => setup_command(&password),
52 Commands::Set { key_value } => set_command(&key_value),
53 Commands::Get { key } => get_command(&key),
54 Commands::Unlock => unlock_command(),
55 Commands::Status => status_command(),
56 Commands::Reset => reset_command(),
57 };
58
59 if let Err(e) = result {
60 eprintln!("❌ {}", e.to_string().red());
61 process::exit(1);
62 }
63}
64
65fn init_command() -> Result<()> {
66 let pb = ProgressBar::new_spinner();
67 pb.set_style(
68 ProgressStyle::default_spinner()
69 .template("{spinner:.green} {msg}")
70 .unwrap()
71 .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
72 );
73 pb.set_message("Initializing vault...");
74 pb.enable_steady_tick(std::time::Duration::from_millis(100));
75
76 let vault = Vault::new();
77 vault.init()?;
78
79 pb.finish_with_message("✅ Vault initialized successfully!");
80 println!("📁 {}", "Created .encrypt directory with secure configuration.".blue());
81
82 Ok(())
83}
84
85fn lockup_command(password: &str) -> Result<()> {
86 let pb = ProgressBar::new_spinner();
87 pb.set_style(
88 ProgressStyle::default_spinner()
89 .template("{spinner:.green} {msg}")
90 .unwrap()
91 .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
92 );
93 pb.set_message("Locking up secrets...");
94 pb.enable_steady_tick(std::time::Duration::from_millis(100));
95
96 let mut vault = Vault::new();
97
98 if !vault.exists() {
99 pb.finish_with_message("❌ Vault not found. Run 'encrypt init' first.");
100 return Err(EncryptError::VaultNotFound);
101 }
102
103 vault.lockup(password)?;
104
105 pb.finish_with_message("✅ Secrets locked successfully!");
106 println!("🔒 {}", "Your secrets are now encrypted and secure.".blue());
107
108 Ok(())
109}
110
111fn setup_command(password: &str) -> Result<()> {
112 let pb = ProgressBar::new_spinner();
113 pb.set_style(
114 ProgressStyle::default_spinner()
115 .template("{spinner:.green} {msg}")
116 .unwrap()
117 .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
118 );
119 pb.set_message("Setting up vault...");
120 pb.enable_steady_tick(std::time::Duration::from_millis(100));
121
122 let mut vault = Vault::new();
123
124 if !vault.exists() {
125 pb.finish_with_message("❌ Vault not found. Run 'encrypt init' first.");
126 return Err(EncryptError::VaultNotFound);
127 }
128
129 vault.setup(password)?;
130
131 pb.finish_with_message("✅ Vault unlocked successfully!");
132 println!("🔓 {}", "Your secrets are now available for use.".blue());
133
134 Ok(())
135}
136
137fn set_command(key_value: &str) -> Result<()> {
138 let parts: Vec<&str> = key_value.splitn(2, '=').collect();
139 if parts.len() != 2 {
140 eprintln!("❌ {}", "Invalid format. Use: encrypt set KEY=value".red());
141 process::exit(1);
142 }
143
144 let key = parts[0];
145 let value = parts[1];
146
147 let pb = ProgressBar::new_spinner();
148 pb.set_style(
149 ProgressStyle::default_spinner()
150 .template("{spinner:.green} {msg}")
151 .unwrap()
152 .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
153 );
154 pb.set_message(format!("Setting secret: {}", key));
155 pb.enable_steady_tick(std::time::Duration::from_millis(100));
156
157 let mut vault = Vault::new();
158
159 if !vault.exists() {
160 pb.finish_with_message("❌ Vault not found. Run 'encrypt init' first.");
161 return Err(EncryptError::VaultNotFound);
162 }
163
164 if !vault.unlocked()? {
165 pb.finish_with_message("❌ Vault is locked. Run 'encrypt setup <password>' to unlock secrets.");
166 return Err(EncryptError::VaultLocked);
167 }
168
169 vault.set(key, value)?;
170
171 pb.finish_with_message(format!("✅ Secret '{}' set successfully!", key));
172
173 Ok(())
174}
175
176fn get_command(key: &str) -> Result<()> {
177 let mut vault = Vault::new();
178
179 if !vault.exists() {
180 eprintln!("❌ {}", "Vault not found. Run 'encrypt init' first.".red());
181 process::exit(1);
182 }
183
184 if !vault.unlocked()? {
185 eprintln!("❌ {}", "Vault is locked. Run 'encrypt setup <password>' to unlock secrets.".red());
186 process::exit(1);
187 }
188
189 let value = vault.get(key)?;
190 println!("{}", value);
191
192 Ok(())
193}
194
195fn unlock_command() -> Result<()> {
196 let pb = ProgressBar::new_spinner();
197 pb.set_style(
198 ProgressStyle::default_spinner()
199 .template("{spinner:.green} {msg}")
200 .unwrap()
201 .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
202 );
203 pb.set_message("Unlocking secrets...");
204 pb.enable_steady_tick(std::time::Duration::from_millis(100));
205
206 let mut vault = Vault::new();
207
208 if !vault.exists() {
209 pb.finish_with_message("❌ Vault not found. Run 'encrypt init' first.");
210 return Err(EncryptError::VaultNotFound);
211 }
212
213 if !vault.unlocked()? {
214 pb.finish_with_message("❌ Vault is locked. Run 'encrypt setup <password>' to unlock secrets.");
215 return Err(EncryptError::VaultLocked);
216 }
217
218 let secrets = vault.all()?;
219 let env_content = secrets
220 .iter()
221 .map(|(k, v)| format!("{}={}", k, v))
222 .collect::<Vec<_>>()
223 .join("\n");
224
225 std::fs::write(".env", env_content)?;
226
227 pb.finish_with_message("✅ Secrets unlocked and written to .env");
228
229 Ok(())
230}
231
232fn status_command() -> Result<()> {
233 let mut vault = Vault::new();
234
235 if !vault.exists() {
236 println!("⚠️ {}", "Vault not found. Run 'encrypt init' first.".yellow());
237 return Ok(());
238 }
239
240 let status = vault.status()?;
241
242 println!("📊 {}", "Vault Status:".blue());
243 println!("┌─────────────────┬──────────────────────────────┐");
244 println!("│ Property │ Value │");
245 println!("├─────────────────┼──────────────────────────────┤");
246
247 let status_icon = if status.is_locked { "🔒" } else { "🔓" };
248 let status_text = if status.is_locked { "Locked" } else { "Unlocked" };
249 let status_color = if status.is_locked { "red" } else { "green" };
250
251 println!(
252 "│ Status │ {} {} │",
253 status_icon,
254 if status_color == "red" {
255 status_text.red()
256 } else {
257 status_text.green()
258 }
259 );
260 println!("│ Keys │ {} │", status.keys.len());
261
262 if let Some(last_modified) = status.last_modified {
263 println!("│ Last Modified │ {} │", last_modified.format("%Y-%m-%dT%H:%M:%S%.3fZ"));
264 }
265
266 println!("└─────────────────┴──────────────────────────────┘");
267
268 if !status.keys.is_empty() {
269 println!("\n🔑 {}", "Available keys:".blue());
270 for key in &status.keys {
271 println!(" • {}", key);
272 }
273 }
274
275 Ok(())
276}
277
278fn reset_command() -> Result<()> {
279 print!("Are you sure you want to reset the vault? This will delete all encrypted secrets. (y/N): ");
280 use std::io::{self, Write};
281 io::stdout().flush()?;
282
283 let mut input = String::new();
284 io::stdin().read_line(&mut input)?;
285 let response = input.trim().to_lowercase();
286
287 if response != "y" && response != "yes" {
288 println!("⚠️ {}", "Reset cancelled.".yellow());
289 return Ok(());
290 }
291
292 let pb = ProgressBar::new_spinner();
293 pb.set_style(
294 ProgressStyle::default_spinner()
295 .template("{spinner:.green} {msg}")
296 .unwrap()
297 .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
298 );
299 pb.set_message("Resetting vault...");
300 pb.enable_steady_tick(std::time::Duration::from_millis(100));
301
302 let vault = Vault::new();
303 vault.reset()?;
304
305 pb.finish_with_message("✅ Vault reset successfully!");
306
307 Ok(())
308}