aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 6fbab0724c33b23df57d96b432a1e9a47bc210b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
use anyhow::{Context, Result};
use clap::{Args, Parser, Subcommand};
use notify::{Config, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::mpsc::channel;
use std::thread;
use std::time::Duration;

/// Error types for reading PID files
#[derive(Debug)]
pub enum PidFileReadError {
    /// The PID file does not exist
    FileNotFound,
    /// The PID file exists but has invalid content
    FileInvalid(String),
    /// IO error occurred while reading
    IoError(std::io::Error),
}

impl std::fmt::Display for PidFileReadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PidFileReadError::FileNotFound => write!(f, "PID file not found"),
            PidFileReadError::FileInvalid(reason) => write!(f, "PID file invalid: {}", reason),
            PidFileReadError::IoError(err) => write!(f, "IO error reading PID file: {}", err),
        }
    }
}

impl std::error::Error for PidFileReadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            PidFileReadError::IoError(err) => Some(err),
            _ => None,
        }
    }
}

/// Represents the contents of a PID file
#[derive(Debug, Clone)]
struct PidFile {
    /// Process ID
    pid: u32,
    /// Command that was executed (program + arguments)
    command: Vec<String>,
}

impl PidFile {
    /// Create a new PidFile instance
    fn new(pid: u32, command: Vec<String>) -> Self {
        Self { pid, command }
    }

    /// Write PID file to a file
    fn write_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let mut file = File::create(path)?;
        writeln!(file, "{}", self.pid)?;
        for arg in &self.command {
            writeln!(file, "{}", arg)?;
        }
        Ok(())
    }

    /// Read PID file from a file
    fn read_from_file<P: AsRef<Path>>(path: P) -> Result<Self, PidFileReadError> {
        let contents = match std::fs::read_to_string(&path) {
            Ok(contents) => contents,
            Err(err) => {
                return if err.kind() == std::io::ErrorKind::NotFound {
                    Err(PidFileReadError::FileNotFound)
                } else {
                    Err(PidFileReadError::IoError(err))
                };
            }
        };

        let lines: Vec<&str> = contents.lines().collect();

        if lines.is_empty() {
            return Err(PidFileReadError::FileInvalid(
                "PID file is empty".to_string(),
            ));
        }

        let pid = lines[0]
            .trim()
            .parse::<u32>()
            .map_err(|_| PidFileReadError::FileInvalid("Invalid PID on first line".to_string()))?;

        let command: Vec<String> = lines[1..].iter().map(|line| line.to_string()).collect();

        if command.is_empty() {
            return Err(PidFileReadError::FileInvalid(
                "No command found in PID file".to_string(),
            ));
        }

        Ok(Self { pid, command })
    }

    /// Get the command as a formatted string for display
    fn command_string(&self) -> String {
        self.command.join(" ")
    }
}

#[derive(Parser)]
#[command(name = "demon")]
#[command(about = "A daemon process management CLI", long_about = None)]
#[command(version)]
#[command(propagate_version = true)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Args)]
struct Global {
    /// Root directory for daemon files (pid, logs). If not specified, searches for git root.
    #[arg(long, global = true, env = "DEMON_ROOT_DIR")]
    root_dir: Option<PathBuf>,
}

#[derive(Subcommand)]
enum Commands {
    /// Spawn a background process and redirect stdout/stderr to files
    Run(RunArgs),

    /// Stop a running daemon process
    Stop(StopArgs),

    /// Tail daemon logs in real-time
    Tail(TailArgs),

    /// Display daemon log contents
    Cat(CatArgs),

    /// List all running daemon processes
    List(ListArgs),

    /// Check status of a daemon process
    Status(StatusArgs),

    /// Clean up orphaned pid and log files
    Clean(CleanArgs),

    /// Output comprehensive usage guide for LLMs
    Llm,

    /// Wait for a daemon process to terminate
    Wait(WaitArgs),
}

#[derive(Args)]
struct RunArgs {
    #[clap(flatten)]
    global: Global,

    /// Process identifier
    id: String,

    /// Command and arguments to execute
    command: Vec<String>,
}

#[derive(Args)]
struct StopArgs {
    #[clap(flatten)]
    global: Global,

    /// Process identifier
    id: String,

    /// Timeout in seconds before sending SIGKILL after SIGTERM
    #[arg(long, default_value = "10")]
    timeout: u64,
}

#[derive(Args)]
struct TailArgs {
    #[clap(flatten)]
    global: Global,

    /// Process identifier
    id: String,

    /// Only tail stdout
    #[arg(long)]
    stdout: bool,

    /// Only tail stderr
    #[arg(long)]
    stderr: bool,

    /// Follow mode - continuously watch for new content (like tail -f)
    #[arg(short = 'f', long)]
    follow: bool,

    /// Number of lines to display from the end (default: 50)
    #[arg(short = 'n', long, default_value = "50")]
    lines: usize,
}

#[derive(Args)]
struct CatArgs {
    #[clap(flatten)]
    global: Global,

    /// Process identifier
    id: String,

    /// Only show stdout
    #[arg(long)]
    stdout: bool,

    /// Only show stderr
    #[arg(long)]
    stderr: bool,
}

#[derive(Args)]
struct ListArgs {
    #[clap(flatten)]
    global: Global,

    /// Quiet mode - output only process data without headers
    #[arg(short, long)]
    quiet: bool,
}

#[derive(Args)]
struct StatusArgs {
    #[clap(flatten)]
    global: Global,

    /// Process identifier
    id: String,
}

#[derive(Args)]
struct CleanArgs {
    #[clap(flatten)]
    global: Global,
}

#[derive(Args)]
struct WaitArgs {
    #[clap(flatten)]
    global: Global,

    /// Process identifier
    id: String,

    /// Timeout in seconds (0 = infinite)
    #[arg(long, default_value = "30")]
    timeout: u64,

    /// Polling interval in seconds
    #[arg(long, default_value = "1")]
    interval: u64,
}

fn main() {
    tracing_subscriber::fmt()
        .with_writer(std::io::stderr)
        .init();

    let cli = Cli::parse();

    if let Err(e) = run_command(cli.command) {
        tracing::error!("Error: {}", e);
        std::process::exit(1);
    }
}

fn run_command(command: Commands) -> Result<()> {
    match command {
        Commands::Run(args) => {
            if args.command.is_empty() {
                return Err(anyhow::anyhow!("Command cannot be empty"));
            }
            let root_dir = resolve_root_dir(&args.global)?;
            run_daemon(&args.id, &args.command, &root_dir)
        }
        Commands::Stop(args) => {
            let root_dir = resolve_root_dir(&args.global)?;
            stop_daemon(&args.id, args.timeout, &root_dir)
        }
        Commands::Tail(args) => {
            let show_stdout = !args.stderr || args.stdout;
            let show_stderr = !args.stdout || args.stderr;
            let root_dir = resolve_root_dir(&args.global)?;
            tail_logs(&args.id, show_stdout, show_stderr, args.follow, args.lines, &root_dir)
        }
        Commands::Cat(args) => {
            let show_stdout = !args.stderr || args.stdout;
            let show_stderr = !args.stdout || args.stderr;
            let root_dir = resolve_root_dir(&args.global)?;
            cat_logs(&args.id, show_stdout, show_stderr, &root_dir)
        }
        Commands::List(args) => {
            let root_dir = resolve_root_dir(&args.global)?;
            list_daemons(args.quiet, &root_dir)
        }
        Commands::Status(args) => {
            let root_dir = resolve_root_dir(&args.global)?;
            status_daemon(&args.id, &root_dir)
        }
        Commands::Clean(args) => {
            let root_dir = resolve_root_dir(&args.global)?;
            clean_orphaned_files(&root_dir)
        }
        Commands::Llm => {
            print_llm_guide();
            Ok(())
        }
        Commands::Wait(args) => {
            let root_dir = resolve_root_dir(&args.global)?;
            wait_daemon(&args.id, args.timeout, args.interval, &root_dir)
        }
    }
}

fn find_git_root() -> Result<PathBuf> {
    let mut current = std::env::current_dir()?;
    
    loop {
        let git_path = current.join(".git");
        if git_path.exists() {
            return Ok(current);
        }
        
        match current.parent() {
            Some(parent) => current = parent.to_path_buf(),
            None => return Err(anyhow::anyhow!(
                "No git repository found. Please specify --root-dir or run from within a git repository"
            )),
        }
    }
}

fn resolve_root_dir(global: &Global) -> Result<PathBuf> {
    match &global.root_dir {
        Some(dir) => {
            if !dir.exists() {
                return Err(anyhow::anyhow!("Specified root directory does not exist: {}", dir.display()));
            }
            if !dir.is_dir() {
                return Err(anyhow::anyhow!("Specified root path is not a directory: {}", dir.display()));
            }
            Ok(dir.clone())
        },
        None => find_git_root(),
    }
}

fn build_file_path(root_dir: &Path, id: &str, extension: &str) -> PathBuf {
    root_dir.join(format!("{}.{}", id, extension))
}

fn run_daemon(id: &str, command: &[String], root_dir: &Path) -> Result<()> {
    let pid_file = build_file_path(root_dir, id, "pid");
    let stdout_file = build_file_path(root_dir, id, "stdout");
    let stderr_file = build_file_path(root_dir, id, "stderr");

    // Check if process is already running
    if is_process_running(&pid_file)? {
        return Err(anyhow::anyhow!("Process '{}' is already running", id));
    }

    tracing::info!("Starting daemon '{}' with command: {:?}", id, command);

    // Truncate/create output files
    File::create(&stdout_file)?;
    File::create(&stderr_file)?;

    // Open files for redirection
    let stdout_redirect = File::create(&stdout_file)?;
    let stderr_redirect = File::create(&stderr_file)?;

    // Spawn the process
    let program = &command[0];
    let args = if command.len() > 1 {
        &command[1..]
    } else {
        &[]
    };

    let child = Command::new(program)
        .args(args)
        .stdout(Stdio::from(stdout_redirect))
        .stderr(Stdio::from(stderr_redirect))
        .stdin(Stdio::null())
        .spawn()
        .with_context(|| format!("Failed to start process '{}' with args {:?}", program, args))?;

    // Write PID and command to file
    let pid_file_data = PidFile::new(child.id(), command.to_vec());
    pid_file_data.write_to_file(&pid_file)?;

    // Don't wait for the child - let it run detached
    std::mem::forget(child);

    println!("Started daemon '{}' with PID written to {}", id, pid_file.display());

    Ok(())
}

fn is_process_running<P: AsRef<Path>>(pid_file: P) -> Result<bool> {
    let pid_file_data = match PidFile::read_from_file(pid_file) {
        Ok(data) => data,
        Err(PidFileReadError::FileNotFound) => return Ok(false), // No PID file means no running process
        Err(PidFileReadError::FileInvalid(_)) => return Ok(false), // Invalid PID file means no running process
        Err(PidFileReadError::IoError(err)) => return Err(err.into()), // Propagate IO errors
    };

    // Check if process is still running using kill -0
    let output = Command::new("kill")
        .args(&["-0", &pid_file_data.pid.to_string()])
        .output()?;

    Ok(output.status.success())
}

fn stop_daemon(id: &str, timeout: u64, root_dir: &Path) -> Result<()> {
    let pid_file = build_file_path(root_dir, id, "pid");

    // Check if PID file exists and read PID data
    let pid_file_data = match PidFile::read_from_file(&pid_file) {
        Ok(data) => data,
        Err(PidFileReadError::FileNotFound) => {
            println!("Process '{}' is not running (no PID file found)", id);
            return Ok(());
        }
        Err(PidFileReadError::FileInvalid(_)) => {
            println!("Process '{}': invalid PID file, removing it", id);
            std::fs::remove_file(&pid_file)?;
            return Ok(());
        }
        Err(PidFileReadError::IoError(err)) => {
            return Err(anyhow::anyhow!("Failed to read PID file: {}", err));
        }
    };

    let pid = pid_file_data.pid;

    tracing::info!(
        "Stopping daemon '{}' (PID: {}) with timeout {}s",
        id,
        pid,
        timeout
    );

    // Check if process is running
    if !is_process_running_by_pid(pid) {
        println!(
            "Process '{}' (PID: {}) is not running, cleaning up PID file",
            id, pid
        );
        std::fs::remove_file(&pid_file)?;
        return Ok(());
    }

    // Send SIGTERM
    tracing::info!("Sending SIGTERM to PID {}", pid);
    let output = Command::new("kill")
        .args(&["-TERM", &pid.to_string()])
        .output()?;

    if !output.status.success() {
        return Err(anyhow::anyhow!("Failed to send SIGTERM to PID {}", pid));
    }

    // Wait for the process to terminate
    for i in 0..timeout {
        if !is_process_running_by_pid(pid) {
            println!("Process '{}' (PID: {}) terminated gracefully", id, pid);
            std::fs::remove_file(&pid_file)?;
            return Ok(());
        }

        if i == 0 {
            tracing::info!("Waiting for process to terminate gracefully...");
        }

        thread::sleep(Duration::from_secs(1));
    }

    // Process didn't terminate, send SIGKILL
    tracing::warn!(
        "Process {} didn't terminate after {}s, sending SIGKILL",
        pid,
        timeout
    );
    let output = Command::new("kill")
        .args(&["-KILL", &pid.to_string()])
        .output()?;

    if !output.status.success() {
        return Err(anyhow::anyhow!("Failed to send SIGKILL to PID {}", pid));
    }

    // Wait a bit more for SIGKILL to take effect
    thread::sleep(Duration::from_secs(1));

    if is_process_running_by_pid(pid) {
        return Err(anyhow::anyhow!(
            "Process {} is still running after SIGKILL",
            pid
        ));
    }

    println!("Process '{}' (PID: {}) terminated forcefully", id, pid);
    std::fs::remove_file(&pid_file)?;

    Ok(())
}

fn is_process_running_by_pid(pid: u32) -> bool {
    let output = Command::new("kill")
        .args(&["-0", &pid.to_string()])
        .output();

    match output {
        Ok(output) => output.status.success(),
        Err(_) => false,
    }
}

fn cat_logs(id: &str, show_stdout: bool, show_stderr: bool, root_dir: &Path) -> Result<()> {
    let stdout_file = build_file_path(root_dir, id, "stdout");
    let stderr_file = build_file_path(root_dir, id, "stderr");

    let mut files_found = false;

    if show_stdout {
        if let Ok(contents) = std::fs::read_to_string(&stdout_file) {
            if !contents.is_empty() {
                files_found = true;
                if show_stderr {
                    println!("==> {} <==", stdout_file.display());
                }
                print!("{}", contents);
            }
        } else {
            tracing::warn!("Could not read {}", stdout_file.display());
        }
    }

    if show_stderr {
        if let Ok(contents) = std::fs::read_to_string(&stderr_file) {
            if !contents.is_empty() {
                files_found = true;
                if show_stdout {
                    println!("==> {} <==", stderr_file.display());
                }
                print!("{}", contents);
            }
        } else {
            tracing::warn!("Could not read {}", stderr_file.display());
        }
    }

    if !files_found {
        println!("No log files found for daemon '{}'", id);
    }

    Ok(())
}

fn tail_logs(
    id: &str,
    show_stdout: bool,
    show_stderr: bool,
    follow: bool,
    lines: usize,
    root_dir: &Path,
) -> Result<()> {
    let stdout_file = build_file_path(root_dir, id, "stdout");
    let stderr_file = build_file_path(root_dir, id, "stderr");

    if !follow {
        // Non-follow mode: just show the last n lines and exit
        let mut files_found = false;

        if show_stdout && stdout_file.exists() {
            let content = read_last_n_lines(&stdout_file, lines)?;
            if !content.is_empty() {
                files_found = true;
                if show_stderr {
                    println!("==> {} <==", stdout_file.display());
                }
                print!("{}", content);
            }
        }

        if show_stderr && stderr_file.exists() {
            let content = read_last_n_lines(&stderr_file, lines)?;
            if !content.is_empty() {
                files_found = true;
                if show_stdout {
                    println!("==> {} <==", stderr_file.display());
                }
                print!("{}", content);
            }
        }

        if !files_found {
            println!("No log files found for daemon '{}'", id);
        }

        return Ok(());
    }

    // Follow mode: original real-time monitoring behavior
    let mut file_positions: std::collections::HashMap<PathBuf, u64> =
        std::collections::HashMap::new();

    if show_stdout && stdout_file.exists() {
        let mut file = File::open(&stdout_file)?;
        let initial_content = read_file_content(&mut file)?;
        if !initial_content.is_empty() {
            if show_stderr {
                println!("==> {} <==", stdout_file.display());
            }
            print!("{}", initial_content);
        }
        let position = file.seek(SeekFrom::Current(0))?;
        file_positions.insert(stdout_file.clone(), position);
    }

    if show_stderr && stderr_file.exists() {
        let mut file = File::open(&stderr_file)?;
        let initial_content = read_file_content(&mut file)?;
        if !initial_content.is_empty() {
            if show_stdout && file_positions.len() > 0 {
                println!("\n==> {} <==", stderr_file.display());
            } else if show_stdout {
                println!("==> {} <==", stderr_file.display());
            }
            print!("{}", initial_content);
        }
        let position = file.seek(SeekFrom::Current(0))?;
        file_positions.insert(stderr_file.clone(), position);
    }

    if file_positions.is_empty() {
        println!(
            "No log files found for daemon '{}'. Watching for new files...",
            id
        );
    }

    tracing::info!("Watching for changes to log files... Press Ctrl+C to stop.");

    // Set up file watcher
    let (tx, rx) = channel();
    let mut watcher = RecommendedWatcher::new(tx, Config::default())?;

    // Watch the root directory for new files and changes
    watcher.watch(root_dir, RecursiveMode::NonRecursive)?;

    // Handle Ctrl+C gracefully
    let running = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
    let r = running.clone();

    ctrlc::set_handler(move || {
        r.store(false, std::sync::atomic::Ordering::SeqCst);
    })?;

    while running.load(std::sync::atomic::Ordering::SeqCst) {
        match rx.recv_timeout(Duration::from_millis(100)) {
            Ok(res) => {
                match res {
                    Ok(Event {
                        kind: EventKind::Modify(_),
                        paths,
                        ..
                    }) => {
                        for path in paths {
                            if (show_stdout && path == stdout_file)
                                || (show_stderr && path == stderr_file)
                            {
                                if let Err(e) = handle_file_change(
                                    &path,
                                    &mut file_positions,
                                    show_stdout && show_stderr,
                                ) {
                                    tracing::error!("Error handling file change: {}", e);
                                }
                            }
                        }
                    }
                    Ok(Event {
                        kind: EventKind::Create(_),
                        paths,
                        ..
                    }) => {
                        // Handle file creation
                        for path in paths {
                            if (show_stdout && path == stdout_file)
                                || (show_stderr && path == stderr_file)
                            {
                                tracing::info!("New file detected: {}", path.display());
                                file_positions.insert(path.clone(), 0);

                                if let Err(e) = handle_file_change(
                                    &path,
                                    &mut file_positions,
                                    show_stdout && show_stderr,
                                ) {
                                    tracing::error!("Error handling new file: {}", e);
                                }
                            }
                        }
                    }
                    Ok(_) => {} // Ignore other events
                    Err(e) => tracing::error!("Watch error: {:?}", e),
                }
            }
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                // Timeout is normal, just continue
            }
            Err(e) => {
                tracing::error!("Receive error: {}", e);
                break;
            }
        }
    }

    println!("\nTailing stopped.");
    Ok(())
}

fn read_file_content(file: &mut File) -> Result<String> {
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    Ok(content)
}

fn read_last_n_lines<P: AsRef<Path>>(file_path: P, n: usize) -> Result<String> {
    let content = std::fs::read_to_string(file_path)?;
    if content.is_empty() {
        return Ok(String::new());
    }

    let lines: Vec<&str> = content.lines().collect();
    let start_index = if lines.len() > n { lines.len() - n } else { 0 };

    let last_lines: Vec<&str> = lines[start_index..].to_vec();
    Ok(last_lines.join("\n") + if content.ends_with('\n') { "\n" } else { "" })
}

fn handle_file_change(
    file_path: &Path,
    positions: &mut std::collections::HashMap<PathBuf, u64>,
    show_headers: bool,
) -> Result<()> {
    let mut file = File::open(file_path)?;
    let current_pos = positions.get(file_path).copied().unwrap_or(0);

    // Seek to the last read position
    file.seek(SeekFrom::Start(current_pos))?;

    // Read new content
    let mut new_content = String::new();
    file.read_to_string(&mut new_content)?;

    if !new_content.is_empty() {
        if show_headers {
            println!("==> {} <==", file_path.display());
        }
        print!("{}", new_content);
        std::io::Write::flush(&mut std::io::stdout())?;

        // Update position
        let new_pos = file.seek(SeekFrom::Current(0))?;
        positions.insert(file_path.to_path_buf(), new_pos);
    }

    Ok(())
}

fn list_daemons(quiet: bool, root_dir: &Path) -> Result<()> {
    if !quiet {
        println!("{:<20} {:<8} {:<10} {}", "ID", "PID", "STATUS", "COMMAND");
        println!("{}", "-".repeat(50));
    }

    let mut found_any = false;

    // Find all .pid files in root directory
    for entry in find_pid_files(root_dir)? {
        found_any = true;
        let path = entry.path();
        let filename = path.file_name()
            .and_then(|name| name.to_str())
            .unwrap_or_default();

        // Extract ID from filename (remove .pid extension)
        let id = filename.strip_suffix(".pid").unwrap_or(filename);

        // Read PID data from file
        match PidFile::read_from_file(&path) {
            Ok(pid_file_data) => {
                let status = if is_process_running_by_pid(pid_file_data.pid) {
                    "RUNNING"
                } else {
                    "DEAD"
                };

                if quiet {
                    println!("{}:{}:{}", id, pid_file_data.pid, status);
                } else {
                    let command = pid_file_data.command_string();
                    println!(
                        "{:<20} {:<8} {:<10} {}",
                        id, pid_file_data.pid, status, command
                    );
                }
            }
            Err(PidFileReadError::FileNotFound) => {
                // This shouldn't happen since we found the file, but handle gracefully
                if quiet {
                    println!("{}:NOTFOUND:ERROR", id);
                } else {
                    println!(
                        "{:<20} {:<8} {:<10} {}",
                        id, "NOTFOUND", "ERROR", "PID file disappeared"
                    );
                }
            }
            Err(PidFileReadError::FileInvalid(reason)) => {
                if quiet {
                    println!("{}:INVALID:ERROR", id);
                } else {
                    println!("{:<20} {:<8} {:<10} {}", id, "INVALID", "ERROR", reason);
                }
            }
            Err(PidFileReadError::IoError(_)) => {
                if quiet {
                    println!("{}:ERROR:ERROR", id);
                } else {
                    println!(
                        "{:<20} {:<8} {:<10} {}",
                        id, "ERROR", "ERROR", "Cannot read PID file"
                    );
                }
            }
        }
    }

    if !found_any && !quiet {
        println!("No daemon processes found.");
    }

    Ok(())
}

fn status_daemon(id: &str, root_dir: &Path) -> Result<()> {
    let pid_file = build_file_path(root_dir, id, "pid");
    let stdout_file = build_file_path(root_dir, id, "stdout");
    let stderr_file = build_file_path(root_dir, id, "stderr");

    println!("Daemon: {}", id);
    println!("PID file: {}", pid_file.display());

    // Read PID data from file
    match PidFile::read_from_file(&pid_file) {
        Ok(pid_file_data) => {
            println!("PID: {}", pid_file_data.pid);
            println!("Command: {}", pid_file_data.command_string());

            if is_process_running_by_pid(pid_file_data.pid) {
                println!("Status: RUNNING");

                // Show file information
                if stdout_file.exists() {
                    let metadata = std::fs::metadata(&stdout_file)?;
                    println!("Stdout file: {} ({} bytes)", stdout_file.display(), metadata.len());
                } else {
                    println!("Stdout file: {} (not found)", stdout_file.display());
                }

                if stderr_file.exists() {
                    let metadata = std::fs::metadata(&stderr_file)?;
                    println!("Stderr file: {} ({} bytes)", stderr_file.display(), metadata.len());
                } else {
                    println!("Stderr file: {} (not found)", stderr_file.display());
                }
            } else {
                println!("Status: DEAD (process not running)");
                println!("Note: Use 'demon clean' to remove orphaned files");
            }
        }
        Err(PidFileReadError::FileNotFound) => {
            println!("Status: NOT FOUND (no PID file)");
        }
        Err(PidFileReadError::FileInvalid(reason)) => {
            println!("Status: ERROR (invalid PID file: {})", reason);
        }
        Err(PidFileReadError::IoError(err)) => {
            println!("Status: ERROR (cannot read PID file: {})", err);
        }
    }

    Ok(())
}

fn clean_orphaned_files(root_dir: &Path) -> Result<()> {
    tracing::info!("Scanning for orphaned daemon files...");

    let mut cleaned_count = 0;

    // Find all .pid files in root directory
    for entry in find_pid_files(root_dir)? {
        let path = entry.path();
        let filename = path.file_name()
            .and_then(|name| name.to_str())
            .unwrap_or_default();
        let id = filename.strip_suffix(".pid").unwrap_or(filename);

        // Read PID data from file
        match PidFile::read_from_file(&path) {
            Ok(pid_file_data) => {
                // Check if process is still running
                if !is_process_running_by_pid(pid_file_data.pid) {
                    println!(
                        "Cleaning up orphaned files for '{}' (PID: {})",
                        id, pid_file_data.pid
                    );

                    // Remove PID file
                    if let Err(e) = std::fs::remove_file(&path) {
                        tracing::warn!("Failed to remove {}: {}", path.display(), e);
                    } else {
                        tracing::info!("Removed {}", path.display());
                    }

                    // Remove stdout file if it exists
                    let stdout_file = build_file_path(root_dir, id, "stdout");
                    if stdout_file.exists() {
                        if let Err(e) = std::fs::remove_file(&stdout_file) {
                            tracing::warn!("Failed to remove {}: {}", stdout_file.display(), e);
                        } else {
                            tracing::info!("Removed {}", stdout_file.display());
                        }
                    }

                    // Remove stderr file if it exists
                    let stderr_file = build_file_path(root_dir, id, "stderr");
                    if stderr_file.exists() {
                        if let Err(e) = std::fs::remove_file(&stderr_file) {
                            tracing::warn!("Failed to remove {}: {}", stderr_file.display(), e);
                        } else {
                            tracing::info!("Removed {}", stderr_file.display());
                        }
                    }

                    cleaned_count += 1;
                } else {
                    tracing::info!(
                        "Skipping '{}' (PID: {}) - process is still running",
                        id,
                        pid_file_data.pid
                    );
                }
            }
            Err(PidFileReadError::FileNotFound) => {
                // This shouldn't happen since we found the file, but handle gracefully
                tracing::warn!("PID file {} disappeared during processing", path.display());
            }
            Err(PidFileReadError::FileInvalid(_)) | Err(PidFileReadError::IoError(_)) => {
                println!("Cleaning up invalid PID file: {}", path.display());
                if let Err(e) = std::fs::remove_file(&path) {
                    tracing::warn!("Failed to remove invalid PID file {}: {}", path.display(), e);
                } else {
                    tracing::info!("Removed invalid PID file {}", path.display());
                    cleaned_count += 1;
                }
            }
        }
    }

    if cleaned_count == 0 {
        println!("No orphaned files found.");
    } else {
        println!("Cleaned up {} orphaned daemon(s).", cleaned_count);
    }

    Ok(())
}

fn print_llm_guide() {
    println!(
        r#"# Demon - Daemon Process Management CLI

## Overview
Demon is a command-line tool for spawning, managing, and monitoring background processes (daemons) on Linux systems. It redirects process stdout/stderr to files and provides commands to control and observe these processes.

## Core Concept
- Each daemon is identified by a unique string ID
- Three files are created per daemon: `<id>.pid`, `<id>.stdout`, `<id>.stderr`
- Files are created in the current working directory
- Processes run detached from the parent shell

## Available Commands

### demon run <identifier> <command...>
Spawns a background process with the given identifier.

**Syntax**: `demon run <id> [--] <command> [args...]`

**Behavior**:
- Creates `<id>.pid`, `<id>.stdout`, `<id>.stderr` files
- Truncates log files if they already exist
- Fails if a process with the same ID is already running
- Parent process exits immediately, child continues in background
- Use `--` to separate flags from command when command has flags

**Examples**:
```bash
demon run web-server python -m http.server 8080
demon run backup-job -- rsync -av /data/ /backup/
demon run log-monitor tail -f /var/log/app.log
```

### demon stop <id> [--timeout <seconds>]
Stops a running daemon process gracefully.

**Syntax**: `demon stop <id> [--timeout <seconds>]`

**Behavior**:
- Sends SIGTERM to the process first
- Waits for specified timeout (default: 10 seconds)
- Sends SIGKILL if process doesn't terminate
- Removes PID file after successful termination
- Handles already-dead processes gracefully

**Examples**:
```bash
demon stop web-server
demon stop backup-job --timeout 30
```

### demon list [--quiet]
Lists all managed daemon processes and their status.

**Syntax**: `demon list [-q|--quiet]`

**Normal Output Format**:
```
ID                   PID      STATUS     COMMAND
--------------------------------------------------
web-server           12345    RUNNING    N/A
backup-job           12346    DEAD       N/A
```

**Quiet Output Format** (machine-readable):
```
web-server:12345:RUNNING
backup-job:12346:DEAD
```

**Status Values**:
- `RUNNING`: Process is actively running
- `DEAD`: Process has terminated, files still exist

### demon status <id>
Shows detailed status information for a specific daemon.

**Syntax**: `demon status <id>`

**Output includes**:
- Daemon ID and PID file location
- Process ID (if available)
- Current status (RUNNING/DEAD/NOT FOUND/ERROR)
- Log file locations and sizes
- Suggestions for cleanup if needed

**Example**:
```bash
demon status web-server
```

### demon cat <id> [--stdout] [--stderr]
Displays the contents of daemon log files.

**Syntax**: `demon cat <id> [--stdout] [--stderr]`

**Behavior**:
- Shows both stdout and stderr by default
- Use flags to show only specific streams
- Displays file headers when showing multiple files
- Handles missing files gracefully

**Examples**:
```bash
demon cat web-server           # Show both logs
demon cat web-server --stdout  # Show only stdout
demon cat web-server --stderr  # Show only stderr
```

### demon tail <id> [--stdout] [--stderr]
Follows daemon log files in real-time (like `tail -f`).

**Syntax**: `demon tail <id> [--stdout] [--stderr]`

**Behavior**:
- Shows existing content first, then follows new content
- Shows both stdout and stderr by default
- Uses file system notifications for efficient monitoring
- Press Ctrl+C to stop tailing
- Handles file creation, rotation, and truncation

**Examples**:
```bash
demon tail web-server           # Follow both logs
demon tail web-server --stdout  # Follow only stdout
```

### demon wait <id> [--timeout <seconds>] [--interval <seconds>]
Blocks until a daemon process terminates.

**Syntax**: `demon wait <id> [--timeout <seconds>] [--interval <seconds>]`

**Behavior**:
- Checks if PID file exists and process is running
- Polls the process every `interval` seconds (default: 1 second)
- Waits for up to `timeout` seconds (default: 30 seconds)
- Use `--timeout 0` for infinite wait
- Exits successfully when process terminates
- Fails with error if process doesn't exist or timeout is reached
- Does not clean up PID files (use `demon clean` for that)

**Examples**:
```bash
demon wait web-server                      # Wait 30s for termination
demon wait backup-job --timeout 0          # Wait indefinitely
demon wait data-processor --timeout 3600   # Wait up to 1 hour
demon wait short-task --interval 2         # Poll every 2 seconds
```

### demon clean
Removes orphaned files from processes that are no longer running.

**Syntax**: `demon clean`

**Behavior**:
- Scans for `.pid` files in current directory
- Checks if corresponding processes are still running
- Removes `.pid`, `.stdout`, `.stderr` files for dead processes
- Handles invalid PID files gracefully
- Reports what was cleaned up

**Example**:
```bash
demon clean
```

## File Management

### Created Files
For each daemon with ID "example":
- `example.pid`: Contains the process ID
- `example.stdout`: Contains standard output from the process
- `example.stderr`: Contains standard error from the process

### File Locations
All files are created in the current working directory where `demon run` is executed.

### Cleanup
- Files persist after process termination for inspection
- Use `demon clean` to remove files from dead processes
- Consider adding `*.pid`, `*.stdout`, `*.stderr` to `.gitignore`

## Common Workflows

### Starting a Web Server
```bash
demon run my-web-server python -m http.server 8080
demon status my-web-server  # Check if it started
demon tail my-web-server    # Monitor logs
```

### Waiting for Process Completion
```bash
demon run batch-job python process_data.py
demon wait batch-job --timeout 600  # Wait up to 10 minutes
demon cat batch-job                  # Check output after completion
```

### Running a Backup Job
```bash
demon run nightly-backup -- rsync -av /data/ /backup/
demon cat nightly-backup   # Check output when done
demon clean                     # Clean up after completion
```

### Managing Multiple Services
```bash
demon run api-server ./api --port 3000
demon run worker-queue ./worker --config prod.conf
demon list                      # See all running services
demon stop api-server      # Stop specific service
```

### Monitoring and Debugging
```bash
demon list --quiet | grep RUNNING  # Machine-readable active processes
demon tail problematic-app --stderr  # Monitor just errors
demon status failing-service         # Get detailed status
```

## Error Handling

### Common Error Scenarios
- **"Process already running"**: Another process with the same ID exists
- **"Command cannot be empty"**: No command specified after `--id`
- **"Process not found"**: No PID file exists for the given ID
- **"Failed to start process"**: Command not found or permission denied

### Best Practices
1. Use descriptive, unique IDs for each daemon
2. Check status before starting to avoid conflicts
3. Use `demon clean` periodically to remove old files
4. Monitor logs with `demon tail` for debugging
5. Use `--timeout` with stop for processes that may take time to shutdown

## Integration Tips

### Scripting
```bash
# Check if service is running
if demon status my-service | grep -q "RUNNING"; then
    echo "Service is running"
fi

# Start service if not running
demon list --quiet | grep -q "my-service:" || demon run my-service ./my-app

# Get machine-readable process list
demon list --quiet > process_status.txt
```

### Process Management
- Demon handles process detachment automatically
- Processes continue running even if demon exits
- Use standard Unix signals for process control
- Log rotation should be handled by the application itself

This tool is designed for Linux environments and provides a simple interface for managing background processes with persistent logging."#
    );
}

fn wait_daemon(id: &str, timeout: u64, interval: u64, root_dir: &Path) -> Result<()> {
    let pid_file = build_file_path(root_dir, id, "pid");

    // Check if PID file exists and read PID data
    let pid_file_data = match PidFile::read_from_file(&pid_file) {
        Ok(data) => data,
        Err(PidFileReadError::FileNotFound) => {
            return Err(anyhow::anyhow!("Process '{}' not found (no PID file)", id));
        }
        Err(PidFileReadError::FileInvalid(reason)) => {
            return Err(anyhow::anyhow!(
                "Process '{}' has invalid PID file: {}",
                id,
                reason
            ));
        }
        Err(PidFileReadError::IoError(err)) => {
            return Err(anyhow::anyhow!(
                "Failed to read PID file for '{}': {}",
                id,
                err
            ));
        }
    };

    let pid = pid_file_data.pid;

    // Check if process is currently running
    if !is_process_running_by_pid(pid) {
        return Err(anyhow::anyhow!("Process '{}' is not running", id));
    }

    tracing::info!("Waiting for process '{}' (PID: {}) to terminate", id, pid);

    // Handle infinite timeout case
    if timeout == 0 {
        loop {
            if !is_process_running_by_pid(pid) {
                tracing::info!("Process '{}' (PID: {}) has terminated", id, pid);
                return Ok(());
            }
            thread::sleep(Duration::from_secs(interval));
        }
    }

    // Handle timeout case
    let mut elapsed = 0;
    while elapsed < timeout {
        if !is_process_running_by_pid(pid) {
            tracing::info!("Process '{}' (PID: {}) has terminated", id, pid);
            return Ok(());
        }

        thread::sleep(Duration::from_secs(interval));
        elapsed += interval;
    }

    // Timeout reached
    Err(anyhow::anyhow!(
        "Timeout reached waiting for process '{}' to terminate",
        id
    ))
}

fn find_pid_files(root_dir: &Path) -> Result<Vec<std::fs::DirEntry>> {
    let entries = std::fs::read_dir(root_dir)?
        .filter_map(|entry| {
            entry.ok().and_then(|e| {
                e.path()
                    .extension()
                    .and_then(|ext| ext.to_str())
                    .filter(|ext| *ext == "pid")
                    .map(|_| e)
            })
        })
        .collect();
    Ok(entries)
}