innisfree 0.4.3

Exposes local services on public IPv4 address, via cloud server.
Documentation
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
//! On-disk layout for per-tunnel state.
//!
//! Centralizes every filename and directory innisfree writes inside its
//! per-service state dir. The previous design scattered string literals
//! (`"ip"`, `"known_hosts"`, `"client_id_ed25519"`) across `manager.rs`,
//! `ssh.rs`, and `wg/mod.rs`, with no compile-time guarantee the writer
//! and reader of a given file agreed on its name. Routing every path
//! through [`TunnelStateDir`] removes that bug surface.
//!
//! XDG split:
//! * **State** (runtime, regenerable-on-bringup) lives under
//!   `$XDG_STATE_HOME/innisfree/<service>/` (default
//!   `~/.local/state/innisfree/<service>/`): lock, `status.json`,
//!   `identity.json`, the ssh keypair files, the rendered wg config.
//! * **Config** (user intent, mirrors the `up` CLI surface) lives at
//!   `$XDG_CONFIG_HOME/innisfree/<service>.toml` (default
//!   `~/.config/innisfree/<service>.toml`). Distinct file per service
//!   sits flat in the config dir so a future user-authored override
//!   (e.g. defaults under `innisfree/defaults.toml`) doesn't collide.
//!
//! Older releases used `~/.config/innisfree/<service>/` for everything;
//! [`TunnelStateDir::for_service`] and [`TunnelStateDir::open`]
//! transparently rename that legacy dir into the state tree on first
//! access so existing `innisfree@.service` units keep working.

use anyhow::{anyhow, bail, Context, Result};
use directories::BaseDirs;
use fs2::FileExt;
use serde::{Deserialize, Serialize};
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::net::IpAddr;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use time::OffsetDateTime;

use crate::config::ServicePort;
use crate::wg::WireguardManager;

/// Filename of the per-tunnel advisory lock (`flock(2)`-style),
/// kept inside the state dir alongside the other artifacts.
const LOCK_FILENAME: &str = ".lock";

/// User-authored input configuration for a single innisfree tunnel.
///
/// Mirrors the `innisfree up` CLI surface 1:1 so a future `attach` or
/// `update` can recover the operator's intent without re-parsing the
/// argv. Written once at bringup (before any cloud-provider calls) to
/// `$XDG_CONFIG_HOME/innisfree/<service>.toml`; the live status —
/// what the tunnel is *actually* doing right now — lives separately in
/// [`TunnelStatus`].
///
/// The provider-specific fields (`region`, `size`, `image`) are flat
/// rather than nested under a `provider` enum because today only
/// DigitalOcean is implemented. A second provider will warrant the
/// refactor; until then a flat schema is one less migration to write.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TunnelConfig {
    /// Cleaned service name (matches the state-dir name).
    pub name: String,
    /// Service ports being forwarded.
    pub services: Vec<ServicePort>,
    /// Destination address local traffic is proxied to.
    pub dest_ip: IpAddr,
    /// Pre-existing reserved IP to attach to the cloud server, if any.
    pub floating_ip: Option<IpAddr>,
    /// Cloud provider kind (today: `"digitalocean"`).
    pub provider: String,
    /// DigitalOcean region slug.
    pub region: String,
    /// DigitalOcean droplet size slug.
    pub size: String,
    /// DigitalOcean image slug.
    pub image: String,
}

/// Crypto identity for a tunnel: the [`WireguardManager`] holding both
/// ends' keypairs and addresses. Written once at bringup alongside the
/// state dir; never rewritten over the tunnel's lifetime. Kept apart
/// from [`TunnelStatus`] so reconfigures (which rewrite status) don't
/// churn key material, and so the file can be mode-`0600` without
/// affecting the readability of `status.json`.
///
/// The ssh client privkey lives at [`TunnelStateDir::client_key`]
/// (mode `0600` already, written by [`crate::ssh::SshKeypair::write_to`])
/// rather than being folded into this file — the on-disk form is
/// functionally required so `ssh -i` can read it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TunnelIdentity {
    /// Both-ends wireguard configuration (keypairs, addresses,
    /// the remote endpoint once known).
    pub wireguard: WireguardManager,
}

/// Structured tunnel readiness record persisted as `status.json` once
/// the wireguard tunnel comes up successfully. Replaces the bare `ip`
/// marker that prior releases used as the readiness signal; the bare
/// file is still written alongside for one release of back-compat
/// (drop in 0.6).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TunnelStatus {
    /// Public IPv4 the tunnel is reachable on.
    pub ip: IpAddr,
    /// Provider-opaque server identifier (e.g. DO droplet ID).
    /// Stored as a String for forward-compat with non-numeric IDs
    /// from future providers.
    pub droplet_id: String,
    /// When the tunnel was confirmed live, in RFC 3339.
    #[serde(with = "time::serde::rfc3339")]
    pub ready_at: OffsetDateTime,
}

/// Handle to the on-disk state directory for a single innisfree tunnel.
///
/// Each tunnel gets its own dir under [`base_dir`], typically
/// `~/.local/state/innisfree/<service>/`. Use [`Self::for_service`] to
/// create the dir (called from `TunnelManager::new`) or [`Self::open`]
/// to reference an already-existing one (called from read-only
/// subcommands like `innisfree ip` and `innisfree ssh`).
///
/// `for_service` takes an exclusive `flock` on `<dir>/.lock` and holds
/// it for the lifetime of the handle, so two `innisfree up --name <s>`
/// invocations cannot race over the same dir. The kernel releases the
/// lock automatically when the process exits, so a crashed prior run
/// does not block a subsequent retry — but in that case [`Self::for_service`]
/// will refuse to proceed if leftover state files are present, to avoid
/// silently overwriting half-written keys. Callers that genuinely want
/// to wipe and start over should call [`remove_state_for_service`] first.
#[derive(Debug)]
pub struct TunnelStateDir {
    path: PathBuf,
    /// Service name, retained because [`Self::wg_conf`] uses it in the
    /// filename (`<service>.conf`).
    name: String,
    /// Exclusive `flock` on `.lock` inside the state dir; held for the
    /// lifetime of the writer-side handle. `None` for [`Self::open`]
    /// (read-only subcommands like `innisfree ip` don't lock so they
    /// can run alongside an active `innisfree up`).
    _lock: Option<File>,
}

impl TunnelStateDir {
    /// Create-or-open the state dir, take an exclusive lock on it, and
    /// refuse to proceed if leftover state from a crashed prior run is
    /// present. Use this from the constructor of long-lived owners
    /// (`TunnelManager::new`).
    ///
    /// Returns an error if another process holds the lock (with the
    /// holder's pid in the message), or if leftover state files remain
    /// from a previous run. The latter case is recoverable by either
    /// running `innisfree clean --name <svc>` or calling
    /// [`remove_state_for_service`] before this constructor — the CLI
    /// surfaces the same choice as `--force`.
    pub fn for_service(service_name: &str) -> Result<Self> {
        let path = base_dir()?.join(service_name);
        migrate_legacy_dir(service_name, &path)?;
        std::fs::create_dir_all(&path)
            .with_context(|| format!("creating state dir {}", path.display()))?;
        let lock = acquire_lock(service_name, &path)?;
        let cfg_file = config_file_for(service_name)?;
        if dir_has_leftover_state(&path)? || cfg_file.exists() {
            bail!(
                "found leftover state at {} (or config at {}) from a previous \
                 `innisfree up --name {service_name}` that did not clean up.\n\
                 Run `innisfree clean --name {service_name}` to wipe it, \
                 or pass `--force` to overwrite.",
                path.display(),
                cfg_file.display(),
            );
        }
        Ok(Self {
            path,
            name: service_name.to_string(),
            _lock: Some(lock),
        })
    }

    /// Open an existing state dir without creating it. Returns an error
    /// if no such dir exists — i.e. the tunnel was never brought up. Use
    /// this for read-only paths like `innisfree ip` and `innisfree ssh`,
    /// where auto-creating an empty dir would just defer the inevitable
    /// "tunnel isn't ready" error and leave a stray directory behind.
    ///
    /// Does *not* take the lock; readers run alongside an active writer.
    pub fn open(service_name: &str) -> Result<Self> {
        let path = base_dir()?.join(service_name);
        migrate_legacy_dir(service_name, &path)?;
        if !path.is_dir() {
            return Err(anyhow!(
                "no state for service '{service_name}' at {} — was the tunnel ever brought up?",
                path.display()
            ));
        }
        Ok(Self {
            path,
            name: service_name.to_string(),
            _lock: None,
        })
    }

    /// Path to the per-service config file in
    /// `$XDG_CONFIG_HOME/innisfree/<service>.toml`. The file is created
    /// lazily by [`Self::write_config`]; callers should not expect it
    /// to exist after [`Self::open`] alone.
    pub fn config_file(&self) -> Result<PathBuf> {
        config_file_for(&self.name)
    }

    /// Path to the on-disk tunnel identity (`identity.json`). Holds
    /// wireguard privkey material so writers must use mode `0600`;
    /// [`Self::write_identity`] enforces this.
    pub fn identity_file(&self) -> PathBuf {
        self.path.join("identity.json")
    }

    /// Persist `config` as TOML at [`Self::config_file`], creating
    /// `$XDG_CONFIG_HOME/innisfree/` if needed.
    pub fn write_config(&self, config: &TunnelConfig) -> Result<()> {
        let path = self.config_file()?;
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("creating config dir {}", parent.display()))?;
        }
        let body = toml::to_string_pretty(config).context("serializing tunnel config to TOML")?;
        std::fs::write(&path, body).with_context(|| format!("writing {}", path.display()))?;
        Ok(())
    }

    /// Load the per-service config TOML if present. Returns `Ok(None)`
    /// when the file does not exist (so the caller can decide whether
    /// that is recoverable — e.g. a tunnel brought up before this
    /// schema existed).
    pub fn read_config(&self) -> Result<Option<TunnelConfig>> {
        let path = self.config_file()?;
        let body = match std::fs::read_to_string(&path) {
            Ok(s) => s,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
        };
        let cfg: TunnelConfig =
            toml::from_str(&body).with_context(|| format!("parsing {}", path.display()))?;
        Ok(Some(cfg))
    }

    /// Persist `identity` as JSON at [`Self::identity_file`], mode
    /// `0600` (the file holds wireguard privkey material). Truncates
    /// any existing file before writing so a rewrite cannot leave
    /// trailing garbage from a longer prior body.
    pub fn write_identity(&self, identity: &TunnelIdentity) -> Result<()> {
        let path = self.identity_file();
        let body =
            serde_json::to_vec_pretty(identity).context("serializing tunnel identity to JSON")?;
        let mut f = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(&path)
            .with_context(|| format!("opening {} for writing", path.display()))?;
        f.write_all(&body)
            .with_context(|| format!("writing {}", path.display()))?;
        Ok(())
    }

    /// Load the on-disk identity if present. Returns `Ok(None)` when
    /// the file does not exist (parallels [`Self::read_config`] and
    /// [`Self::read_status`]).
    pub fn read_identity(&self) -> Result<Option<TunnelIdentity>> {
        let path = self.identity_file();
        let bytes = match std::fs::read(&path) {
            Ok(b) => b,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
        };
        let id: TunnelIdentity = serde_json::from_slice(&bytes)
            .with_context(|| format!("parsing {}", path.display()))?;
        Ok(Some(id))
    }

    /// Path to the structured tunnel status (`status.json`). Written
    /// by [`crate::manager::TunnelManager::up`] after the wireguard
    /// tunnel is verified live; consumed by
    /// [`crate::manager::get_server_ip`] (and the scheduled Phase 2
    /// operator reconcile loop). See [`TunnelStatus`] for the shape.
    pub fn status_file(&self) -> PathBuf {
        self.path.join("status.json")
    }

    /// Bare-IP marker file. Kept alongside [`Self::status_file`] for
    /// one release of back-compat with anything scripting against
    /// `~/.local/state/innisfree/<svc>/ip`; drop in 0.6.
    pub fn ip_marker(&self) -> PathBuf {
        self.path.join("ip")
    }

    /// Persist `status` as JSON to [`Self::status_file`], also
    /// emitting the bare-IP back-compat marker.
    pub fn write_status(&self, status: &TunnelStatus) -> Result<()> {
        let json_path = self.status_file();
        let json =
            serde_json::to_vec_pretty(status).context("serializing tunnel status to JSON")?;
        std::fs::write(&json_path, &json)
            .with_context(|| format!("writing {}", json_path.display()))?;
        // Back-compat: keep writing the bare `ip` file for one release
        // so existing scripts that `cat ~/.local/state/innisfree/<n>/ip`
        // keep working. Drop in 0.6.
        let ip_path = self.ip_marker();
        std::fs::write(&ip_path, format!("{}\n", status.ip))
            .with_context(|| format!("writing {}", ip_path.display()))?;
        Ok(())
    }

    /// Load `status.json` if present. Returns `Ok(None)` when the
    /// file doesn't exist (e.g. tunnel still coming up, or pre-0.5
    /// state dir) so the caller can decide to fall back to the bare
    /// `ip` marker.
    pub fn read_status(&self) -> Result<Option<TunnelStatus>> {
        let path = self.status_file();
        let bytes = match std::fs::read(&path) {
            Ok(b) => b,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => {
                return Err(e).with_context(|| format!("reading {}", path.display()));
            }
        };
        let status: TunnelStatus = serde_json::from_slice(&bytes)
            .with_context(|| format!("parsing {}", path.display()))?;
        Ok(Some(status))
    }

    /// SSH `known_hosts` file pinning the remote sshd's host key.
    pub fn known_hosts(&self) -> PathBuf {
        self.path.join("known_hosts")
    }

    /// Client-side SSH private key path. The matching public key lives
    /// at the same location with `.pub` appended. (No `server_key`
    /// counterpart: the remote sshd's keypair never lives on disk
    /// locally — it travels via cloud-init.)
    pub fn client_key(&self) -> PathBuf {
        self.path.join("client_id_ed25519")
    }

    /// Rendered `wg0.conf` path for the local end of the tunnel. The
    /// filename includes the service name so multiple parallel tunnels
    /// don't collide if a future change ever flattens the layout.
    pub fn wg_conf(&self) -> PathBuf {
        self.path.join(format!("{}.conf", self.name))
    }
}

/// Recursively delete the state dir for `service_name` and remove the
/// per-service config file at `$XDG_CONFIG_HOME/innisfree/<svc>.toml`.
/// Idempotent — returns `Ok(())` if neither exists. Used by the
/// `clean` subcommand and by `TunnelManager::clean` during teardown.
pub fn remove_state_for_service(service_name: &str) -> Result<()> {
    let path = base_dir()?.join(service_name);
    if path.is_dir() {
        std::fs::remove_dir_all(&path).with_context(|| format!("removing {}", path.display()))?;
    }
    let cfg = config_file_for(service_name)?;
    if cfg.exists() {
        std::fs::remove_file(&cfg).with_context(|| format!("removing config {}", cfg.display()))?;
    }
    Ok(())
}

/// One-shot migration from the legacy `~/.config/innisfree/<svc>/`
/// path. If `target` does not yet exist but a legacy dir for the same
/// service does, rename it. After migration the legacy dir is gone —
/// no double-writes — so this is a no-op on every subsequent call.
fn migrate_legacy_dir(service_name: &str, target: &Path) -> Result<()> {
    if target.exists() {
        return Ok(());
    }
    let Some(legacy) = legacy_base_dir().map(|p| p.join(service_name)) else {
        return Ok(());
    };
    if !legacy.is_dir() {
        return Ok(());
    }
    if let Some(parent) = target.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("creating state parent {}", parent.display()))?;
    }
    std::fs::rename(&legacy, target).with_context(|| {
        format!(
            "migrating legacy state {} -> {}",
            legacy.display(),
            target.display()
        )
    })?;
    tracing::info!(
        "migrated legacy state dir {} -> {}",
        legacy.display(),
        target.display()
    );
    Ok(())
}

/// Resolve the parent dir under which all per-tunnel state lives:
/// `$XDG_STATE_HOME/innisfree/`, defaulting to
/// `$HOME/.local/state/innisfree/` when the env var is unset.
fn base_dir() -> Result<PathBuf> {
    let bd = BaseDirs::new().ok_or_else(|| anyhow!("could not resolve home directory"))?;
    let state_root = bd
        .state_dir()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| bd.home_dir().join(".local").join("state"));
    Ok(state_root.join("innisfree"))
}

/// Resolve the parent dir for user-authored config:
/// `$XDG_CONFIG_HOME/innisfree/`, defaulting to
/// `$HOME/.config/innisfree/`. Per-service config files live flat
/// inside, one TOML per service.
fn config_base_dir() -> Result<PathBuf> {
    let bd = BaseDirs::new().ok_or_else(|| anyhow!("could not resolve home directory"))?;
    Ok(bd.config_dir().join("innisfree"))
}

/// Path the per-service config TOML lands at, computed without
/// requiring a [`TunnelStateDir`] in hand. Used by
/// [`remove_state_for_service`] and [`TunnelStateDir::for_service`]'s
/// leftover-detection.
fn config_file_for(service_name: &str) -> Result<PathBuf> {
    Ok(config_base_dir()?.join(format!("{service_name}.toml")))
}

/// Resolve the legacy parent dir (`$HOME/.config/innisfree/`). Used
/// only by [`migrate_legacy_dir`].
fn legacy_base_dir() -> Option<PathBuf> {
    BaseDirs::new().map(|bd| bd.home_dir().join(".config").join("innisfree"))
}

/// Take an exclusive `flock(2)` on `<dir>/.lock`. Stamps the current
/// pid into the file on success so any subsequent contender's error
/// message can identify the holder. Returns `Err` with a user-facing
/// message if another process already holds the lock.
fn acquire_lock(service_name: &str, dir: &Path) -> Result<File> {
    let lock_path = dir.join(LOCK_FILENAME);
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&lock_path)
        .with_context(|| format!("opening lock file {}", lock_path.display()))?;
    if let Err(e) = file.try_lock_exclusive() {
        // Best-effort: report the pid that previous holders stamped
        // into the file. Falls back to a generic message if the file
        // is unreadable / empty / non-numeric.
        let holder_pid = std::fs::read_to_string(&lock_path)
            .ok()
            .and_then(|s| s.trim().parse::<u32>().ok());
        let detail = match holder_pid {
            Some(pid) => format!("(pid {pid} holds the lock)"),
            None => format!("(lock at {} held)", lock_path.display()),
        };
        return Err(anyhow!(e)).with_context(|| {
            format!("another `innisfree up --name {service_name}` appears to be running {detail}")
        });
    }
    // We own the lock — stamp our pid into the file so any later
    // contender's error message can name us.
    file.set_len(0)
        .with_context(|| format!("truncating {}", lock_path.display()))?;
    writeln!(&file, "{}", std::process::id())
        .with_context(|| format!("writing pid to {}", lock_path.display()))?;
    Ok(file)
}

/// Return true iff `dir` contains anything besides the lock file —
/// i.e. leftover state from a previous run. Called immediately after
/// [`acquire_lock`], so the only file we expect to find on the happy
/// path is `.lock` itself.
fn dir_has_leftover_state(dir: &Path) -> Result<bool> {
    for entry in
        std::fs::read_dir(dir).with_context(|| format!("reading state dir {}", dir.display()))?
    {
        let entry = entry?;
        if entry.file_name() != LOCK_FILENAME {
            return Ok(true);
        }
    }
    Ok(false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn for_service_uses_xdg_state_home() {
        let td = TempDir::new().unwrap();
        let state_root = td.path().join("state");
        let home = td.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let state_str = state_root.to_str().unwrap();
        let home_str = home.to_str().unwrap();
        temp_env::with_vars(
            [
                ("XDG_STATE_HOME", Some(state_str)),
                ("HOME", Some(home_str)),
            ],
            || {
                let dir = TunnelStateDir::for_service("svc-fresh").unwrap();
                let expected = state_root.join("innisfree").join("svc-fresh");
                assert_eq!(dir.path, expected);
                assert!(expected.is_dir());
            },
        );
    }

    #[test]
    fn migrates_from_legacy_config_dir() {
        let td = TempDir::new().unwrap();
        let home = td.path().join("home");
        let state_root = td.path().join("state");
        std::fs::create_dir_all(&home).unwrap();
        let legacy = home.join(".config").join("innisfree").join("svc-mig");
        std::fs::create_dir_all(&legacy).unwrap();
        std::fs::write(legacy.join("ip"), "1.2.3.4\n").unwrap();

        let state_str = state_root.to_str().unwrap();
        let home_str = home.to_str().unwrap();
        temp_env::with_vars(
            [
                ("XDG_STATE_HOME", Some(state_str)),
                ("HOME", Some(home_str)),
            ],
            || {
                let dir = TunnelStateDir::open("svc-mig").unwrap();
                let expected = state_root.join("innisfree").join("svc-mig");
                assert_eq!(dir.path, expected);
                assert!(expected.join("ip").is_file());
                assert!(!legacy.exists());
            },
        );
    }

    #[test]
    fn for_service_writes_pid_into_lock_file() {
        let td = TempDir::new().unwrap();
        let state_root = td.path().join("state");
        let home = td.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let state_str = state_root.to_str().unwrap();
        let home_str = home.to_str().unwrap();
        temp_env::with_vars(
            [
                ("XDG_STATE_HOME", Some(state_str)),
                ("HOME", Some(home_str)),
            ],
            || {
                let dir = TunnelStateDir::for_service("svc-pid").unwrap();
                let lock = dir.path.join(LOCK_FILENAME);
                let recorded: u32 = std::fs::read_to_string(&lock)
                    .unwrap()
                    .trim()
                    .parse()
                    .unwrap();
                assert_eq!(recorded, std::process::id());
            },
        );
    }

    #[test]
    fn second_for_service_call_blocks_on_lock() {
        let td = TempDir::new().unwrap();
        let state_root = td.path().join("state");
        let home = td.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let state_str = state_root.to_str().unwrap();
        let home_str = home.to_str().unwrap();
        temp_env::with_vars(
            [
                ("XDG_STATE_HOME", Some(state_str)),
                ("HOME", Some(home_str)),
            ],
            || {
                let first = TunnelStateDir::for_service("svc-busy").unwrap();
                let err = TunnelStateDir::for_service("svc-busy").unwrap_err();
                let chain: String = err
                    .chain()
                    .map(|c| format!("{c}"))
                    .collect::<Vec<_>>()
                    .join(" / ");
                let pid = std::process::id();
                assert!(
                    chain.contains(&format!("pid {pid}")),
                    "expected pid in error chain, got: {chain}"
                );
                drop(first);
                // After the holder drops, a new acquisition must succeed.
                let _second = TunnelStateDir::for_service("svc-busy").unwrap();
            },
        );
    }

    #[test]
    fn for_service_rejects_leftover_state() {
        let td = TempDir::new().unwrap();
        let state_root = td.path().join("state");
        let home = td.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        // Pre-populate the new-layout dir with a stale state file as if
        // a prior run crashed mid-flight.
        let stale = state_root.join("innisfree").join("svc-stale");
        std::fs::create_dir_all(&stale).unwrap();
        std::fs::write(stale.join("ip"), "9.9.9.9\n").unwrap();

        let state_str = state_root.to_str().unwrap();
        let home_str = home.to_str().unwrap();
        temp_env::with_vars(
            [
                ("XDG_STATE_HOME", Some(state_str)),
                ("HOME", Some(home_str)),
            ],
            || {
                let err = TunnelStateDir::for_service("svc-stale").unwrap_err();
                let msg = format!("{err:#}");
                assert!(
                    msg.contains("leftover state") && msg.contains("--force"),
                    "expected leftover-state guidance, got: {msg}"
                );
            },
        );
    }

    #[test]
    fn status_round_trips_through_status_json() {
        let td = TempDir::new().unwrap();
        let state_root = td.path().join("state");
        let home = td.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let state_str = state_root.to_str().unwrap();
        let home_str = home.to_str().unwrap();
        temp_env::with_vars(
            [
                ("XDG_STATE_HOME", Some(state_str)),
                ("HOME", Some(home_str)),
            ],
            || {
                let dir = TunnelStateDir::for_service("svc-status").unwrap();
                let written = TunnelStatus {
                    ip: "203.0.113.7".parse().unwrap(),
                    droplet_id: "12345".to_string(),
                    ready_at: OffsetDateTime::from_unix_timestamp(1_700_000_000).unwrap(),
                };
                dir.write_status(&written).unwrap();

                // status.json is parseable JSON containing the right ip + id.
                let raw = std::fs::read_to_string(dir.path.join("status.json")).unwrap();
                assert!(raw.contains("\"ip\""), "status.json missing ip: {raw}");
                assert!(
                    raw.contains("\"droplet_id\": \"12345\""),
                    "status.json missing droplet_id: {raw}"
                );
                assert!(
                    raw.contains("2023-11-14T22:13:20Z"),
                    "status.json missing rfc3339 ready_at: {raw}"
                );

                // Bare ip marker is also written for back-compat (drop in 0.6).
                let bare = std::fs::read_to_string(dir.path.join("ip")).unwrap();
                assert_eq!(bare.trim(), "203.0.113.7");

                // read_status round-trips.
                let read = dir.read_status().unwrap().unwrap();
                assert_eq!(read.ip, written.ip);
                assert_eq!(read.droplet_id, written.droplet_id);
                assert_eq!(read.ready_at, written.ready_at);
            },
        );
    }

    #[test]
    fn read_status_returns_none_when_file_absent() {
        let td = TempDir::new().unwrap();
        let state_root = td.path().join("state");
        let home = td.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let state_str = state_root.to_str().unwrap();
        let home_str = home.to_str().unwrap();
        temp_env::with_vars(
            [
                ("XDG_STATE_HOME", Some(state_str)),
                ("HOME", Some(home_str)),
            ],
            || {
                let dir = TunnelStateDir::for_service("svc-no-status").unwrap();
                // Fresh dir → no status.json yet.
                assert!(dir.read_status().unwrap().is_none());
            },
        );
    }

    #[test]
    fn config_round_trips_through_xdg_config_home() {
        let td = TempDir::new().unwrap();
        let state_root = td.path().join("state");
        let cfg_root = td.path().join("config");
        let home = td.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let state_str = state_root.to_str().unwrap();
        let cfg_str = cfg_root.to_str().unwrap();
        let home_str = home.to_str().unwrap();
        temp_env::with_vars(
            [
                ("XDG_STATE_HOME", Some(state_str)),
                ("XDG_CONFIG_HOME", Some(cfg_str)),
                ("HOME", Some(home_str)),
            ],
            || {
                let dir = TunnelStateDir::for_service("svc-cfg").unwrap();
                let written = TunnelConfig {
                    name: "svc-cfg".to_string(),
                    services: ServicePort::from_str_multi("80/TCP,443/TCP").unwrap(),
                    dest_ip: "127.0.0.1".parse().unwrap(),
                    floating_ip: Some("198.51.100.7".parse().unwrap()),
                    provider: "digitalocean".to_string(),
                    region: "sfo3".to_string(),
                    size: "s-1vcpu-1gb".to_string(),
                    image: "debian-13-x64".to_string(),
                };
                dir.write_config(&written).unwrap();

                let expected = cfg_root.join("innisfree").join("svc-cfg.toml");
                assert_eq!(dir.config_file().unwrap(), expected);
                assert!(
                    expected.is_file(),
                    "config file not written at {expected:?}"
                );

                let raw = std::fs::read_to_string(&expected).unwrap();
                assert!(raw.contains("provider = \"digitalocean\""), "{raw}");
                assert!(raw.contains("region = \"sfo3\""), "{raw}");

                let read = dir.read_config().unwrap().unwrap();
                assert_eq!(read.name, written.name);
                assert_eq!(read.dest_ip, written.dest_ip);
                assert_eq!(read.floating_ip, written.floating_ip);
                assert_eq!(read.region, written.region);
                assert_eq!(read.services.len(), written.services.len());
            },
        );
    }

    #[test]
    fn read_config_returns_none_when_file_absent() {
        let td = TempDir::new().unwrap();
        let state_root = td.path().join("state");
        let cfg_root = td.path().join("config");
        let home = td.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        temp_env::with_vars(
            [
                ("XDG_STATE_HOME", Some(state_root.to_str().unwrap())),
                ("XDG_CONFIG_HOME", Some(cfg_root.to_str().unwrap())),
                ("HOME", Some(home.to_str().unwrap())),
            ],
            || {
                let dir = TunnelStateDir::for_service("svc-no-cfg").unwrap();
                assert!(dir.read_config().unwrap().is_none());
            },
        );
    }

    #[test]
    fn identity_round_trips_and_is_mode_0600() {
        use std::os::unix::fs::PermissionsExt;
        let td = TempDir::new().unwrap();
        let state_root = td.path().join("state");
        let cfg_root = td.path().join("config");
        let home = td.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        temp_env::with_vars(
            [
                ("XDG_STATE_HOME", Some(state_root.to_str().unwrap())),
                ("XDG_CONFIG_HOME", Some(cfg_root.to_str().unwrap())),
                ("HOME", Some(home.to_str().unwrap())),
            ],
            || {
                let dir = TunnelStateDir::for_service("svc-id").unwrap();
                let wg = WireguardManager::new("svc-id").unwrap();
                let written = TunnelIdentity {
                    wireguard: wg.clone(),
                };
                dir.write_identity(&written).unwrap();

                let id_path = dir.identity_file();
                assert!(id_path.is_file());
                let mode = std::fs::metadata(&id_path).unwrap().permissions().mode();
                // Only inspect the low 9 bits — type bits aren't relevant.
                assert_eq!(
                    mode & 0o777,
                    0o600,
                    "identity.json must be 0600, got {:o}",
                    mode & 0o777,
                );

                let read = dir.read_identity().unwrap().unwrap();
                // Round-trip the actually-load-bearing fields (the
                // keypair bytes); the addresses already get covered by
                // create_manager in wg::tests.
                assert_eq!(
                    read.wireguard
                        .local_device
                        .interface
                        .keypair
                        .public_bytes()
                        .unwrap(),
                    wg.local_device.interface.keypair.public_bytes().unwrap(),
                );
                assert_eq!(
                    read.wireguard
                        .local_device
                        .interface
                        .keypair
                        .private_bytes()
                        .unwrap(),
                    wg.local_device.interface.keypair.private_bytes().unwrap(),
                );
                assert_eq!(
                    read.wireguard.remote_device.interface.address,
                    wg.remote_device.interface.address,
                );
            },
        );
    }

    #[test]
    fn remove_state_drops_config_file_too() {
        let td = TempDir::new().unwrap();
        let state_root = td.path().join("state");
        let cfg_root = td.path().join("config");
        let home = td.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        temp_env::with_vars(
            [
                ("XDG_STATE_HOME", Some(state_root.to_str().unwrap())),
                ("XDG_CONFIG_HOME", Some(cfg_root.to_str().unwrap())),
                ("HOME", Some(home.to_str().unwrap())),
            ],
            || {
                let svc = "svc-clean";
                let dir = TunnelStateDir::for_service(svc).unwrap();
                let cfg = TunnelConfig {
                    name: svc.to_string(),
                    services: vec![],
                    dest_ip: "127.0.0.1".parse().unwrap(),
                    floating_ip: None,
                    provider: "digitalocean".to_string(),
                    region: "sfo3".to_string(),
                    size: "s-1vcpu-1gb".to_string(),
                    image: "debian-13-x64".to_string(),
                };
                dir.write_config(&cfg).unwrap();
                let cfg_path = dir.config_file().unwrap();
                let state_path = dir.path.clone();
                drop(dir); // release the flock before wiping

                assert!(cfg_path.is_file());
                assert!(state_path.is_dir());

                remove_state_for_service(svc).unwrap();

                assert!(!cfg_path.exists(), "config file survived clean");
                assert!(!state_path.exists(), "state dir survived clean");

                // Idempotent: a second call on already-clean state is Ok.
                remove_state_for_service(svc).unwrap();
            },
        );
    }

    #[test]
    fn for_service_rejects_leftover_config() {
        let td = TempDir::new().unwrap();
        let state_root = td.path().join("state");
        let cfg_root = td.path().join("config");
        let home = td.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        // Pre-populate the config file as if a prior bringup crashed
        // after writing it but before the state dir gathered any
        // other artifacts. The lock won't be held (kernel released it
        // on the dead process exit), so the bare-file check is the
        // only guard against a silent overwrite.
        let cfg_path = cfg_root.join("innisfree").join("svc-cfg-stale.toml");
        std::fs::create_dir_all(cfg_path.parent().unwrap()).unwrap();
        std::fs::write(&cfg_path, "name = \"svc-cfg-stale\"\n").unwrap();

        temp_env::with_vars(
            [
                ("XDG_STATE_HOME", Some(state_root.to_str().unwrap())),
                ("XDG_CONFIG_HOME", Some(cfg_root.to_str().unwrap())),
                ("HOME", Some(home.to_str().unwrap())),
            ],
            || {
                let err = TunnelStateDir::for_service("svc-cfg-stale").unwrap_err();
                let msg = format!("{err:#}");
                assert!(
                    msg.contains("leftover state") && msg.contains("--force"),
                    "expected leftover guidance mentioning config, got: {msg}"
                );
            },
        );
    }

    #[test]
    fn migration_is_noop_when_no_legacy_dir() {
        let td = TempDir::new().unwrap();
        let home = td.path().join("home");
        let state_root = td.path().join("state");
        std::fs::create_dir_all(&home).unwrap();

        let state_str = state_root.to_str().unwrap();
        let home_str = home.to_str().unwrap();
        temp_env::with_vars(
            [
                ("XDG_STATE_HOME", Some(state_str)),
                ("HOME", Some(home_str)),
            ],
            || {
                let dir = TunnelStateDir::for_service("svc-virgin").unwrap();
                let expected = state_root.join("innisfree").join("svc-virgin");
                assert_eq!(dir.path, expected);
                assert!(expected.is_dir());
            },
        );
    }
}