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
use std::{process::Command, fmt::Debug, io::{Error, ErrorKind}, fs};
use std::str::from_utf8;

#[cfg(target_os = "linux")]
#[derive(Debug)]
pub struct LinuxEntity {
    pub entity_name: String,
    pub entity_type: String,
    pub owner: String,
    pub group: String,
    pub hardlink: u8,
    pub permission: u16,
    pub size: i32,
    pub last_change_date: String,
}

#[cfg(target_os = "linux")]
pub struct Permissions<'a> {
    pub entity_type: &'a str,
    pub permission: u16
}

#[cfg(target_os = "linux")]
fn decode_permission_string(perm_string: &str) -> Permissions {
    let file_type = perm_string.chars().next().unwrap_or(' ');
    let ft = match file_type {
        '-' => "file",
        'd' => "folder",
        'l' => "symlink",
        _ => panic!("Invalid file type character: {}", file_type),
    };

    let permissions = &perm_string[1..10]; 
    let mut permission_value = 0;

    for (i, chunk) in permissions.chars().collect::<Vec<char>>().chunks(3).enumerate() {
        let mut chunk_value = 0;
        if chunk[0] == 'r' {
            chunk_value += 4;
        }
        if chunk[1] == 'w' {
            chunk_value += 2;
        }
        if chunk[2] == 'x' {
            chunk_value += 1;
        }
        permission_value += chunk_value * 10u16.pow(2 - i as u32);
    }

    Permissions {
        entity_type: ft,
        permission: permission_value,
    }
}

#[cfg(target_os = "linux")]
pub fn current_folder_info() -> Vec<LinuxEntity> {
    let check_permission = Command::new("sudo").arg("ls").arg("-l").output().unwrap();
    let mut entities: Vec<LinuxEntity> = vec![];
    let output = from_utf8(&check_permission.stdout).unwrap();

    for (index, line) in output.lines().into_iter().enumerate() {
        if index == 0 {
            continue;
        }

        let split_the_line: Vec<&str> = line.split_whitespace().collect();

        let perm_str = decode_permission_string(split_the_line[0]);

        let new_entity = LinuxEntity {
            entity_name: split_the_line[8].to_string(),
            entity_type: perm_str.entity_type.to_string(),
            permission: perm_str.permission,
            owner: split_the_line[2].to_string(),
            group: split_the_line[3].to_string(),
            hardlink: split_the_line[1].parse().unwrap(),
            size: split_the_line[4].parse().unwrap(),
            last_change_date: format!("{} {} {}", split_the_line[5], split_the_line[6], split_the_line[7])
        };

        entities.push(new_entity);
    }

    return entities;
}

#[cfg(target_os = "linux")]
pub fn other_folder_info(path: &str) -> Result<Vec<LinuxEntity>, Error> {
    let check_permission = Command::new("sudo").arg("ls").arg("-l").arg(path).output().unwrap();
    let mut entities: Vec<LinuxEntity> = vec![];
    let output = from_utf8(&check_permission.stdout).unwrap();

    if !&output.starts_with("total ") {
        return Err(Error::new(ErrorKind::InvalidInput, "Invalid input. If you want to check a file, use 'check_file()' function instead."));
    }

    for (index, line) in output.lines().into_iter().enumerate() {
        if index == 0 {
            continue;
        }

        let split_the_line: Vec<&str> = line.split_whitespace().collect();

        let perm_str = decode_permission_string(split_the_line[0]);

        let new_entity = LinuxEntity {
            entity_name: split_the_line[8].to_string(),
            entity_type: perm_str.entity_type.to_string(),
            permission: perm_str.permission,
            owner: split_the_line[2].to_string(),
            group: split_the_line[3].to_string(),
            hardlink: split_the_line[1].parse().unwrap(),
            size: split_the_line[4].parse().unwrap(),
            last_change_date: format!("{} {} {}", split_the_line[5], split_the_line[6], split_the_line[7])
        };

        entities.push(new_entity);
    }

    return Ok(entities);
}

#[cfg(target_os = "linux")]
pub fn file_info(path: &str) -> Result<LinuxEntity, Error> {
    let run_command = Command::new("sudo").arg("ls").arg("-l").arg(path).output().unwrap();
    let output = from_utf8(&run_command.stdout).unwrap();

    if output.starts_with("total ") {
        return Err(Error::new(ErrorKind::InvalidInput, "Invalid input. If you want to check a folder, use 'check_other_folder()' function instead."))
    }

    let split_the_output: Vec<&str> = output.split_whitespace().collect();

    let perm_str = decode_permission_string(split_the_output[0]);

    Ok(LinuxEntity {
        entity_name: split_the_output[8].to_string(),
        entity_type: perm_str.entity_type.to_string(),
        permission: perm_str.permission,
        owner: split_the_output[2].to_string(),
        group: split_the_output[3].to_string(),
        hardlink: split_the_output[1].parse().unwrap(),
        size: split_the_output[4].parse().unwrap(),
        last_change_date: format!("{} {} {}", split_the_output[5], split_the_output[6], split_the_output[7])
    })
}

#[cfg(target_os = "linux")]
pub fn is_file(path: &str) -> bool {
    let run_command = Command::new("sudo").arg("ls").arg("-l").arg(path).output().unwrap();
    let output = from_utf8(&run_command.stdout).unwrap();

    if output.starts_with("-") {
        return true;
    } else {
        return false;
    }
} 

#[cfg(target_os = "linux")]
pub fn is_folder(path: &str) -> bool {
    let run_command = Command::new("sudo").arg("ls").arg("-l").arg(path).output().unwrap();
    let output = from_utf8(&run_command.stdout).unwrap();

    if output.starts_with("total ") {
        return true;
    } else {
        return false;
    }
}

#[cfg(target_os = "linux")]
pub fn is_symlink(path: &str) -> bool {
    let run_command = Command::new("sudo").arg("ls").arg("-l").arg(path).output().unwrap();
    let output = from_utf8(&run_command.stdout).unwrap();

    if output.starts_with("l") {
        return true;
    } else {
        return false;
    }
}

pub fn is_exist(path: &str) -> bool {
    if fs::metadata(path).is_ok() {
        true
    } else {
        false
    }
}

// şimdi yukarıdaki ufule'nin yapdığının aynısını tek bir başka bir klasör ve bir dosya için
// yapan ufuleleri de yaz.

#[cfg(target_os = "linux")]
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_decode_permission_string(){
        let perm_str = decode_permission_string("-rw-r--r--");

        assert_eq!(perm_str.permission, 644 as u16);
        assert_eq!(perm_str.entity_type, "file");
    }

    #[test]
    fn test_current_folder_info() {
        println!("Current Folder's Entities: {:#?}", current_folder_info())
    }

    #[test]
    fn test_other_folder_info(){
        println!("/sys/dev/block folder's entities: {:#?}", other_folder_info("/sys/dev/block"))
    }

    #[test]
    fn test_file_info(){
        println!("Check 1:0 file: {:#?}", file_info("/sys/dev/block/1:0"))
    }

    #[test]
    fn test_is_file(){
        assert_eq!(true, is_file("Cargo.toml"))
    }

    #[test]
    fn test_is_folder() {
        assert_eq!(false, is_folder("Cargo.toml"))
    }

    #[test]
    fn test_is_symlink(){
        assert_eq!(true, is_symlink("/sys/dev/block/1:0"))
    }

    #[test]
    fn test_is_exist(){
        assert_eq!(false, is_exist("dfsgdfsgd"))
    }
}