use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};

use reqwest;

#[tokio::main]
async fn main() {
    create().await.unwrap();
    println!("1. Disable mangle rules: {}", ":foreach i in=[/ip firewall mangle find comment=\"breakwall\"] do={ /ip firewall mangle disable $i }");
    println!("2. Remove old CIDR list: {}", ":foreach i in=[/ip firewall address_list find list=chn_list ] do={/ip firewall address_list remove number=$i }");
    println!("3. Load new CIDR list: {}", "/import chn_list.rsc");
    println!("4. Enable mangle rules: {}", ":foreach i in=[/ip firewall mangle find comment=\"breakwall\"] do={ /ip firewall mangle enable $i }");
}

async fn create() -> Result<(), Box<dyn Error>> {
    let url = "https://ispip.clang.cn/all_cn.txt";
    let dest = "chn_list.rsc";
    let mut dest = File::create(dest).unwrap();
    // address list name
    let list = "chn_list";
    let clean_command = format!(":foreach i in=[/ip/firewall/address-list/find list=\"{}\"] do={{remove numbers=$i}}\n", list);
    dest.write(clean_command.as_bytes()).unwrap();
    // request china cidr from network
    let text = reqwest::get(url).await?
        .text().await?;
    let lines = text.lines();
    let lines = lines.collect::<Vec<&str>>();
    write_to_file(&mut dest, list, &lines);
    // additional network
    let additional = File::open("additional.txt").unwrap();
    let lines = BufReader::new(additional).lines();
    for x in lines {
        let cidr = x.unwrap();
        let cidr = cidr.trim();
        if !cidr.is_empty() && !cidr.starts_with("#") {
            let vec1 = vec![cidr];
            write_to_file(&mut dest, list, &vec1);
        };
    }
    Ok(())
}

fn write_to_file(file: &mut File, list: &str, address_list: &Vec<&str>) {
    for x in address_list {
        let line = format!("/ip/firewall/address-list add list={} address={}\n", list, x);
        file.write(line.as_bytes()).unwrap();
    }
}
