netweft 0.2.0

Deterministic network planning and configuration generation for portable infrastructure.
Documentation
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};

use crate::paths::NetweftPaths;
use crate::plan::ssh::{ResolvedSshPlan, ResolvedSshTarget};

pub fn render_ssh(plan: &ResolvedSshPlan, paths: &NetweftPaths) -> Result<PathBuf> {
    let output = paths
        .generated_dir
        .join(&plan.location)
        .join("clients")
        .join(&plan.client)
        .join("ssh");

    if output.exists() {
        fs::remove_dir_all(&output)
            .with_context(|| format!("failed to clean {}", output.display()))?;
    }

    let snippets = output.join("config.d/netweft");
    fs::create_dir_all(&snippets)?;

    for target in &plan.targets {
        write(
            &snippets.join(format!("{}.conf", target.alias)),
            &target_config(target),
        )?;
    }

    write(&output.join("action-plan.txt"), &action_plan(plan))?;
    write(&output.join("install.sh"), install_script())?;
    write(&output.join("rollback.sh"), rollback_script())?;
    write(&output.join("verify.sh"), &verify_script(plan))?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;

        for name in ["install.sh", "rollback.sh", "verify.sh"] {
            fs::set_permissions(output.join(name), fs::Permissions::from_mode(0o755))?;
        }
    }

    Ok(output)
}

fn action_plan(plan: &ResolvedSshPlan) -> String {
    let mut output = format!(
        "Generated by Netweft. Review before applying.\n\nClient: {}\nLocation: {}\nOwnership: ~/.ssh/config.d/netweft only\n\n",
        plan.client, plan.location
    );

    for target in &plan.targets {
        output.push_str(&format!(
            "{} -> {}@{}:{} identity={} forward-agent={} source={}\n",
            target.alias,
            target.user,
            target.host_name,
            target.port,
            target.identity_file,
            target.forward_agent,
            target.source
        ));
    }

    output
}

fn target_config(target: &ResolvedSshTarget) -> String {
    let mut output = format!(
        "# Generated by Netweft. Do not edit.\n# Source: {}\nHost {}\n  HostName {}\n  User {}\n  Port {}\n  IdentityFile {}\n  IdentitiesOnly yes\n",
        target.source,
        target.alias,
        target.host_name,
        target.user,
        target.port,
        target.identity_file,
    );

    if target.forward_agent {
        output.push_str("  ForwardAgent yes\n");
    }

    output
}

fn install_script() -> &'static str {
    r#"#!/usr/bin/env bash
set -euo pipefail

script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
ssh_dir="${SSH_DIR:-$HOME/.ssh}"
config_parent="$ssh_dir/config.d"
target_dir="$config_parent/netweft"
backup="$HOME/.local/state/netweft/ssh-backups/$(date +%Y%m%d-%H%M%S)"

mkdir -p "$backup" "$config_parent" "$ssh_dir/controlpath"
chmod 700 "$ssh_dir" "$config_parent" "$ssh_dir/controlpath"

# Validate the generated snippets before touching the active configuration.
preflight=$(mktemp)
staging=""

cleanup() {
  rm -f "$preflight"
  if [ -n "$staging" ] && [ -d "$staging" ]; then
    rm -rf "$staging"
  fi
}
trap cleanup EXIT

printf 'Include "%s"\n' \
  "$script_dir/config.d/netweft/*.conf" > "$preflight"

for alias in $(awk '/^Host / {print $2}' "$script_dir"/config.d/netweft/*.conf); do
  ssh -F "$preflight" -G "$alias" >/dev/null
done

staging=$(mktemp -d "$config_parent/.netweft.XXXXXX")

for file in "$script_dir"/config.d/netweft/*.conf; do
  [ -e "$file" ] || continue
  install -m 0600 "$file" "$staging/$(basename "$file")"
done

if [ -d "$target_dir" ]; then
  mv "$target_dir" "$backup/netweft"
fi

mv "$staging" "$target_dir"
staging=""
chmod 700 "$target_dir"

# Validate through the real Helix-owned ~/.ssh/config include chain.
for alias in $(awk '/^Host / {print $2}' "$target_dir"/*.conf); do
  ssh -G "$alias" >/dev/null
done

echo "Installed Netweft SSH aliases."
echo "Backup: $backup"
"#
}

fn rollback_script() -> &'static str {
    r#"#!/usr/bin/env bash
set -euo pipefail

backup=${1:?usage: rollback.sh BACKUP_DIRECTORY}
ssh_dir="${SSH_DIR:-$HOME/.ssh}"
config_parent="$ssh_dir/config.d"
target_dir="$config_parent/netweft"

mkdir -p "$config_parent"
rm -rf "$target_dir"

if [ -d "$backup/netweft" ]; then
  cp -a "$backup/netweft" "$target_dir"
  chmod 700 "$target_dir"
fi

echo "Restored Netweft SSH aliases from $backup"
"#
}

fn verify_script(plan: &ResolvedSshPlan) -> String {
    let mut output = String::from(
        "#!/usr/bin/env bash\n\
         set -euo pipefail\n\n\
         test -f \"$HOME/.ssh/config\"\n\
         test -d \"$HOME/.ssh/config.d/netweft\"\n\n",
    );

    for target in &plan.targets {
        output.push_str(&format!(
            "echo '=== {} ==='\n\
             ssh -G {} | grep -E '^(hostname|user|port|identityfile|forwardagent) '\n\n",
            target.alias,
            shell_word(&target.alias)
        ));
    }

    output
}

fn shell_word(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

fn write(path: &Path, contents: &str) -> Result<()> {
    fs::write(path, contents).with_context(|| format!("failed to write {}", path.display()))
}