//
// Syd: rock-solid application kernel
// src/syd-emacs.rs: Syd's secure Emacs wrapper
//
// Copyright (c) 2024 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

use std::{
    os::unix::process::CommandExt,
    process::{Command, ExitCode},
};

use nix::{fcntl::OFlag, sys::stat::Mode, unistd::Uid};
use syd::err::SydResult;

fn main() -> SydResult<ExitCode> {
    syd::set_sigpipe_dfl()?;

    // Determine HOME directory.
    let uid = Uid::current();
    let name = syd::get_user_name(uid);
    let home = syd::get_user_home(&name);
    let conf = home.join(b".emacs.d/init.syd-3");

    // Prepare command.
    let mut cmd = Command::new("syd");

    // Set up logging.
    let mut buf = itoa::Buffer::new();
    let logf = home.join(b".emacs.d/syd.log");
    #[allow(clippy::disallowed_methods)]
    let file = nix::fcntl::open(
        &logf,
        OFlag::O_CREAT | OFlag::O_APPEND,
        Mode::from_bits_truncate(0o600),
    )?;
    cmd.env("SYD_LOG_FD", buf.format(file));

    // Set up arguments.
    let argv: Vec<String> = std::env::args().skip(1).collect();
    if conf.exists(true) {
        cmd.arg("-P");
        cmd.arg(conf);
    } else {
        cmd.arg("-plib");
    }
    cmd.args(["--", "emacs", "--load=/dev/syd.el"]);
    cmd.args(&argv);

    // Execute Emacs under Syd!
    Err(cmd.exec().into())
}
