dentimoer_setup/
lib.rs

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
use std::process::Command;
use std::fs;
use std::io;
use std::path::Path;
use regex::Regex;
use std::thread;
use std::time::Duration;

pub fn install_essential_equipments() -> io::Result<()> {
    let choco_install_cmd = "Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))";
    
    let ttest = "ls";
    let set_opencv_include_paths = "";
    let get_opencv_world_version = get_opencv_num_and_version_test();
    let set_opencv_link_paths = "";
    let set_opencv_bin_paths = "C:\\tools\\opencv\\build\\x64\\vc16\\bin";

    match call_admin_powershell(&ttest) {
        Ok(exit_code) => {
            println!("First ls command completed with exit code: {}", exit_code);
            thread::sleep(Duration::from_secs(2));
            
            // dir 명령어 실행
            match call_admin_powershell("dir") {
                Ok(exit_code) => {
                    println!("Dir command completed with exit code: {}", exit_code);
                    thread::sleep(Duration::from_secs(2));
                    
                    // 두 번째 ls 명령어 실행
                    match call_admin_powershell("ls") {
                        Ok(exit_code) => {
                            println!("Second ls command completed with exit code: {}", exit_code);
                            thread::sleep(Duration::from_secs(2));

                            match call_admin_powershell("dir") {
                                Ok(exit_code) => {
                                    println!("The dir third completed with exit code: {}", exit_code);
                                    thread::sleep(Duration::from_secs(2));
                                    Ok(())
                                },
                                Err(e) => {
                                    eprintln!("The third dir failed: {}", e);
                                    Err(e)
                                }
                            }
                        },
                        Err(e) => {
                            eprintln!("Second ls command failed: {}", e);
                            Err(e)
                        }
                    }
                },
                Err(e) => {
                    eprintln!("Dir command failed: {}", e);
                    Err(e)
                }
            }
        },
        Err(e) => {
            eprintln!("First ls command failed: {}", e);
            Err(e)
        }
    }

    // 첫 번째 명령어 실행 및 완료 대기
    /*match call_admin_powershell("ls") {
        Ok(exit_code) => {
            println!("First ls command completed with exit code: {}", exit_code);
            thread::sleep(Duration::from_secs(2));
            
            // dir 명령어 실행
            match call_admin_powershell("dir") {
                Ok(exit_code) => {
                    println!("Dir command completed with exit code: {}", exit_code);
                    thread::sleep(Duration::from_secs(2));
                    
                    // 두 번째 ls 명령어 실행
                    match call_admin_powershell("ls") {
                        Ok(exit_code) => {
                            println!("Second ls command completed with exit code: {}", exit_code);
                            Ok(())
                        },
                        Err(e) => {
                            eprintln!("Second ls command failed: {}", e);
                            Err(e)
                        }
                    }
                },
                Err(e) => {
                    eprintln!("Dir command failed: {}", e);
                    Err(e)
                }
            }
        },
        Err(e) => {
            eprintln!("First ls command failed: {}", e);
            Err(e)
        }
    }*/
}

pub fn call_admin_powershell(cmd: &str) -> io::Result<u32> {
    let output = Command::new("powershell")
        .arg("-Command")
        .arg(format!(
            "Start-Process PowerShell -ArgumentList '-Command', '{}' -Verb RunAs -Wait",
            cmd
        ))
        .output()?;

    if output.status.success() {
        println!("Command '{}' executed successfully.", cmd);
        Ok(output.status.code().unwrap_or(0) as u32)
    } else {
        let error_message = String::from_utf8_lossy(&output.stderr);
        eprintln!("Command '{}' failed: {}", cmd, error_message);
        Err(io::Error::new(
            io::ErrorKind::Other,
            format!("Command execution failed: {}", error_message)
        ))
    }
}

pub fn get_opencv_num_and_version_test() -> Option<u32> {
    let opencv_lib_path = "C:\\tools\\opencv\\build\\x64\\lib"; // OpenCV 라이브러리 경로
    let opencv_world_prefix = "opencv_world";

    // 라이브러리 경로가 존재하는지 확인
    if !Path::new(opencv_lib_path).exists() {
        eprintln!("OpenCV 라이브러리 경로가 존재하지 않습니다: {}", opencv_lib_path);
        return None;
    }

    // 디렉토리에서 파일 목록 읽기
    match fs::read_dir(opencv_lib_path) {
        Ok(entries) => {
            // opencv_world 뒤의 숫자를 찾기 위한 정규식
            let re = Regex::new(&format!(r"{}(\d+)\.lib", opencv_world_prefix)).unwrap();

            for entry in entries {
                if let Ok(entry) = entry {
                    let file_name = entry.file_name();
                    let file_name = file_name.to_string_lossy();

                    // 정규식에 매칭되는 파일 찾기
                    if let Some(captures) = re.captures(&file_name) {
                        if let Some(version_str) = captures.get(1) {
                            if let Ok(version) = version_str.as_str().parse::<u32>() {
                                println!("발견된 OpenCV 라이브러리: {}", file_name);
                                println!("추출된 버전 숫자: {}", version);
                                return Some(version); // 버전을 u16 값으로 반환
                            } else {
                                eprintln!("버전 숫자가 u16 형식으로 변환되지 않습니다.");
                                return None;
                            }
                        }
                    }
                }
            }

            println!("opencv_world 라이브러리를 찾을 수 없습니다.");
            None
        }
        Err(e) => {
            eprintln!("디렉토리를 읽을 수 없습니다: {}", e);
            None
        }
    }
}

pub fn set_opencv_env_test(opencv_version: u32) { // for windows 11
    let opencv_include_paths = "C:\\tools\\opencv\\build\\include";
    let opencv_link_string = format!("opencv_world{}", opencv_version);
    let opencv_link_libs = opencv_link_string.as_str();
    let opencv_link_paths = "C:\\tools\\opencv\\build\\x64\\lib";
    let opencv_bin_paths = "C:\\tools\\opencv\\build\\x64\\vc16\\bin";

    // 명령어를 실행하기 위한 PowerShell 스크립트 생성
    let script = format!(
        r#"
        [Environment]::SetEnvironmentVariable('OPENCV_INCLUDE_PATHS', '{0}', [EnvironmentVariableTarget]::Machine)
        [Environment]::SetEnvironmentVariable('OPENCV_LINK_LIBS', '{1}', [EnvironmentVariableTarget]::Machine)
        [Environment]::SetEnvironmentVariable('OPENCV_LINK_PATHS', '{2}', [EnvironmentVariableTarget]::Machine)
        $currentPath = [Environment]::GetEnvironmentVariable('Path', [EnvironmentVariableTarget]::Machine)
        if (-not ($currentPath -like '*{3}*')) {{
            [Environment]::SetEnvironmentVariable('Path', \"$currentPath;{3}\", [EnvironmentVariableTarget]::Machine)
        }}
        "#,
        opencv_include_paths, opencv_link_libs, opencv_link_paths, opencv_bin_paths
    );

    // PowerShell 명령 실행
    let output = Command::new("powershell")
        .args(["-Command", &script])
        .output()
        .expect("Failed to execute PowerShell command");

    // 결과 출력
    if output.status.success() {
        println!("환경 변수가 성공적으로 설정되었습니다.");
    } else {
        eprintln!(
            "오류 발생: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
}