use anyhow::Context;
use std::ffi::OsString;
use std::fs::{self, File};
use std::io;
use std::os::unix::ffi::OsStringExt;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use tempfile::TempDir;

const S_IFMT: u32 = 0o170000;
const S_IFLNK: u32 = 0o120000;
const S_ISUID: u32 = 0o4000;
const S_ISGID: u32 = 0o2000;
const S_ISVTX: u32 = 0o1000;

/// A file with setuid/setgid set, or a directory with the sticky bit set,
/// found in a zip archive. `mode` is the permission bits including the
/// special bits (e.g. `0o6644` for a file with both setuid and setgid).
pub struct SpecialBitFinding {
    pub name: PathBuf,
    pub mode: u32,
    pub is_dir: bool,
    pub setuid: bool,
    pub setgid: bool,
    pub sticky: bool,
}

/// Scans a zip archive (without extracting it) for files with setuid/setgid
/// set or directories with the sticky bit set. These bits are never applied
/// during extraction (`extract()` masks them off), so this is a read-only
/// audit of what the archive contains.
pub fn scan_special_bits(zip_path: &str) -> anyhow::Result<Vec<SpecialBitFinding>> {
    let file = File::open(zip_path).with_context(|| format!("failed to open {zip_path}"))?;
    let mut archive = zip::ZipArchive::new(file)
        .with_context(|| format!("failed to read TDS zip archive {zip_path}"))?;

    let mut findings = Vec::new();
    for i in 0..archive.len() {
        let entry = archive.by_index(i)?;
        let (Some(name), Some(mode)) = (entry.enclosed_name(), entry.unix_mode()) else {
            continue;
        };
        // zip >= 9 clears the special bits in unix_mode(); restore them from
        // the raw attributes (DOS archives carry no Unix mode there).
        let mode = if entry.system() == zip::System::Dos {
            mode
        } else {
            mode | (entry.external_attributes() >> 16) & 0o7000
        };

        let setuid = !entry.is_dir() && mode & S_ISUID != 0;
        let setgid = !entry.is_dir() && mode & S_ISGID != 0;
        let sticky = entry.is_dir() && mode & S_ISVTX != 0;

        if setuid || setgid || sticky {
            findings.push(SpecialBitFinding {
                name,
                mode: mode & 0o7777,
                is_dir: entry.is_dir(),
                setuid,
                setgid,
                sticky,
            });
        }
    }
    Ok(findings)
}

/// A zip archive extracted into a temp directory. The directory (with the
/// archive's original permission bits applied) is removed automatically
/// when this value is dropped.
pub struct ExtractedZip {
    dir: TempDir,
}

impl ExtractedZip {
    pub fn path(&self) -> &Path {
        self.dir.path()
    }
}

impl Drop for ExtractedZip {
    fn drop(&mut self) {
        // Deleting the tree requires write permission on every directory in
        // it (removing an entry needs write access on its parent, not the
        // entry itself), so a restrictive extracted mode (e.g. 555) would
        // otherwise make cleanup fail silently. Best-effort: if this fails,
        // TempDir's own drop will just leave behind whatever it can't remove.
        let _ = make_writable(self.dir.path());
    }
}

pub fn extract(zip_path: &str) -> anyhow::Result<ExtractedZip> {
    let file = File::open(zip_path).with_context(|| format!("failed to open {zip_path}"))?;
    let mut archive = zip::ZipArchive::new(file)
        .with_context(|| format!("failed to read zip archive {zip_path}"))?;

    let dest = tempfile::Builder::new()
        .prefix("pkgcheck")
        .tempdir()
        .with_context(|| "creating tempdir".to_string())?;

    // Extract manually (rather than archive.extract()) so directory permission
    // bits get applied too -- the zip crate's own extract() only applies the
    // stored mode to files, not directories.
    //
    // Directory modes are applied in a second pass, deepest-first, after all
    // files are written: a restrictive mode (e.g. 555) on a parent would
    // otherwise block creating files in its children during extraction.
    let mut dir_modes = Vec::new();

    for i in 0..archive.len() {
        let mut entry = archive.by_index(i)?;
        let Some(name) = entry.enclosed_name() else {
            continue;
        };
        let out_path = dest.path().join(&name);

        let is_symlink = entry
            .unix_mode()
            .is_some_and(|mode| mode & S_IFMT == S_IFLNK);

        if entry.is_dir() {
            fs::create_dir_all(&out_path)?;
            if let Some(mode) = entry.unix_mode() {
                dir_modes.push((out_path, mode));
            }
        } else if is_symlink {
            if let Some(parent) = out_path.parent() {
                fs::create_dir_all(parent)?;
            }
            // A symlink entry's "file content" is the link target path, not
            // real file data.
            let mut target_bytes = Vec::new();
            io::copy(&mut entry, &mut target_bytes)?;
            let target = PathBuf::from(OsString::from_vec(target_bytes));
            std::os::unix::fs::symlink(&target, &out_path)?;
        } else {
            if let Some(parent) = out_path.parent() {
                fs::create_dir_all(parent)?;
            }
            let mut out_file = File::create(&out_path)?;
            io::copy(&mut entry, &mut out_file)?;
            if let Some(mode) = entry.unix_mode() {
                fs::set_permissions(&out_path, fs::Permissions::from_mode(mode & 0o777))?;
            }
        }
    }

    dir_modes.sort_by_key(|(path, _)| std::cmp::Reverse(path.components().count()));
    for (path, mode) in &dir_modes {
        fs::set_permissions(path, fs::Permissions::from_mode(mode & 0o777))?;
    }

    Ok(ExtractedZip { dir: dest })
}

fn make_writable(dir: &Path) -> io::Result<()> {
    for entry in fs::read_dir(dir)? {
        let path = entry?.path();
        // Use symlink_metadata (doesn't follow symlinks) so a symlink
        // pointing at a directory isn't mistaken for one -- recursing into
        // it would chmod/traverse a directory outside the extracted tree.
        if fs::symlink_metadata(&path)?.file_type().is_dir() {
            let mut perms = fs::metadata(&path)?.permissions();
            perms.set_mode(perms.mode() | 0o700);
            fs::set_permissions(&path, perms)?;
            make_writable(&path)?;
        }
    }
    Ok(())
}
