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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
//! Client. Fetches location data from GNSS (GPS), Mobile Country Code from GSM, WiFi/Bluetooth/GSM cell
//! based geolocation from the Libreloc server, and GeoIP from RIPE NCC.
//! It estimates the location using heuristics.

use anyhow::{bail, ensure, Context, Result};
use axum::{
    extract::State,
    http::StatusCode,
    response::IntoResponse,
    routing::{get, post},
    Router,
};
use bytes::Bytes;
use hex::FromHex;
use log::{debug, error, info, LevelFilter};
use rand::distributions::{Alphanumeric, DistString};
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use sailfish::TemplateOnce;
use serde::Deserialize;
use std::net::IpAddr;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
use std::{collections::HashMap, time::Instant};
use structopt::StructOpt;
use systemd_journal_logger::JournalLog;
use tokio::fs;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;
use tokio::sync::mpsc;
use tokio::time::{self, sleep, Duration};

use libreloc_shared::*;

use geohash::Coord;

#[derive(Clone)]
struct AppState {
    conf: Conf,
    location_state: Arc<Mutex<HashMap<SrcKind, Source>>>,
    location: Arc<Mutex<Plocation>>,
}

/// An internal source of geolocation data
#[derive(Debug, Clone)]
struct Source {
    name: String,
    last_plocation: Plocation,
    last_update_time: Instant,
    // average_accuracy: f32,
}

#[derive(Debug, PartialEq, Eq, Hash, Clone)]
enum SrcKind {
    Gnss,
    GsmCountry,
    WifiBt,
    // WiFiRegulatoryDomain
    // AnycastDns,
    // LatencyProbe,
}

#[derive(Debug)]
struct Update {
    plocation: Plocation,
    extra: Option<String>,
    src_kind: SrcKind,
    last_update_time: Instant,
}

// fn generate_keypair() -> () {
//     let mut csprng = OsRng {};
//     let keypair: Keypair = Keypair::generate(&mut csprng);
//     let secret_key_base64 = base64::encode(&keypair.secret.to_bytes());
// }

type Sender = tokio::sync::mpsc::Sender<Update>;
type Receiver = tokio::sync::mpsc::Receiver<Update>;

// ----- Configuration -----

/// Configuration
#[derive(Deserialize, Debug, Clone)]
struct Conf {
    conf_version: u8,
    upload_url: Option<String>,
    fetch_url: Option<String>,
    listen_addr: Option<String>,
}
// TODO implement RawConf

/// Loads configuration from file. Supports simple overrides.
fn load_conf() -> Result<Conf> {
    let conf_fn =
        std::env::var("CONF_FN").unwrap_or_else(|_| "/etc/libreloc_client.json".to_string());
    info!("[main] reading {}", conf_fn);
    let jc = std::fs::read_to_string(&conf_fn)
        .with_context(|| format!("Unable to read config file '{}'", &conf_fn))?;

    let conf: Conf = serde_json::from_str(&jc)
        .with_context(|| format!("Unable to parse configuration in '{}'", &conf_fn))?;

    debug!("[main] conf loaded");
    ensure!(
        conf.conf_version == 1,
        "Invalid configuration format version. Must be 1"
    );

    Ok(conf)
}

// ----- GNSS -----

#[allow(dead_code)]
#[derive(Deserialize, Debug)]
struct Tpv {
    class: String,
    device: Option<String>,
    mode: Option<u8>,
    time: Option<String>,
    ept: Option<f64>,
    lat: Option<f64>,
    lon: Option<f64>,
    alt: Option<f64>,
    epx: Option<f64>,
    epy: Option<f64>,
    epv: Option<f64>,
}

#[derive(Deserialize, Debug)]
struct GpsdResponse {
    tpv: Vec<Tpv>,
}

async fn gnss_reader(chan: Sender) -> Result<()> {
    const URL: &str = "http://localhost:2947/stream?device=json";
    let reqc = reqwest::Client::new();

    loop {
        let resp: GpsdResponse = reqc.get(URL).send().await?.json().await?;

        if let Some(tpv) = resp.tpv.first() {
            if let (Some(lat), Some(lon), Some(accuracy)) = (tpv.lat, tpv.lon, tpv.epx) {
                let up = Update {
                    plocation: Plocation {
                        loc: Coord { x: lon, y: lat },
                        lsm: accuracy as f32,
                    },
                    extra: None,
                    src_kind: SrcKind::Gnss,
                    last_update_time: Instant::now(),
                };
                chan.send(up).await.unwrap();
            } else {
                info!("[gnss] Location data is not available yet.");
            }
        }

        sleep(Duration::from_secs(5)).await;
    }
}

// ----- IPaddr based geolocation using 3rd party services -----

async fn fetch_public_ipaddr(reqc: &reqwest::Client) -> Result<String> {
    const IPADDR_LOOKUP_URL: &str = "https://ifconfig.co/ip";
    let resp = reqc
        .get(IPADDR_LOOKUP_URL)
        .header(reqwest::header::USER_AGENT, "libreloc-client")
        .send()
        .await
        .context("Failed to send request")?;

    if !resp.status().is_success() {
        return Err(anyhow::anyhow!("Request failed"));
    }
    let ipaddr = resp.text().await?;
    let ipaddr = ipaddr.trim();
    let _: IpAddr = ipaddr.parse()?; // Validity check
    Ok(ipaddr.to_string())
}

#[derive(Deserialize, Debug)]
struct RipeIpmapBestRespLoc {
    latitude: f64,
    longitude: f64,
}

#[derive(Deserialize, Debug)]
struct RipeIpmapBestResp {
    location: Option<RipeIpmapBestRespLoc>,
}

async fn geoip_prober_one(reqc: &reqwest::Client) -> Result<Coord> {
    let ipaddr = fetch_public_ipaddr(reqc).await?;
    let url = format!(
        "https://ipmap-api.ripe.net/v1/locate/{}/best?client=libreloc-client",
        ipaddr
    );
    debug!("[geoip] fetching {}", url);
    let resp = reqc
        .get(url)
        .header(reqwest::header::USER_AGENT, "libreloc-client")
        .send()
        .await
        .context("Failed to send request")?;

    if !resp.status().is_success() {
        return Err(anyhow::anyhow!("Request failed"));
    }

    debug!("[geoip] decoding json");
    let resp: RipeIpmapBestResp = resp.json().await?;
    debug!("[geoip] received {:?}", resp);
    let r = match resp.location {
        Some(v) => v,
        None => return Err(anyhow::anyhow!("Request failed")),
    };
    Ok(Coord {
        y: r.latitude,
        x: r.longitude,
    })
}

/// Uses 3rd party services to fetch the current public IP address and resolve it
/// to a geolocation. RIPE IPmap uses many methods including crowdsourced data,
/// latency and anycast and other heuristics to identify a location.
async fn geoip_prober(chan: Sender) {
    let reqc = reqwest::Client::new();
    loop {
        let c = match geoip_prober_one(&reqc).await {
            Ok(c) => c,
            Err(e) => {
                error!("[geoip] {:?}", e);
                time::sleep(Duration::from_secs(3600 * 4)).await;
                continue;
            }
        };
        let up = Update {
            plocation: Plocation {
                loc: c,
                lsm: 500_000.0, // TODO: better estimation
            },
            extra: None,
            src_kind: SrcKind::Gnss,
            last_update_time: Instant::now(),
        };
        chan.send(up).await.unwrap();
        time::sleep(Duration::from_secs(3600)).await;
    }
}

// ----- GSM MCC -----

/// Fetch the MCC (Mobile Country Code) from a GSM if present
async fn fetch_gsm_mcc() -> Result<Option<String>> {
    // Run nmcli
    let p = Command::new("nmcli")
        .args(["-t", "-f", "GSM.OPERATOR.ID", "device", "status"])
        .output()
        .await
        .context("Failed to run nmcli")?;

    if !p.status.success() {
        let stderr = String::from_utf8_lossy(&p.stderr);
        if stderr.contains("GSM.OPERATOR.ID") {
            return Ok(None);
        }
        bail!("nmcli command failed with: {}", stderr);
    }

    let stdout = String::from_utf8_lossy(&p.stdout);
    if stdout.trim().is_empty() {
        Ok(None)
    } else {
        let op_id = stdout.trim();
        let mcc = &op_id[0..3]; // first three digits are the MCC
        Ok(Some(mcc.into()))
    }
}

async fn gsm_country_code_reader(chan: tokio::sync::mpsc::Sender<Update>) {
    loop {
        info!("[gsm] gsm MCC");
        let mcc = match fetch_gsm_mcc().await {
            Ok(Some(mcc)) => mcc,
            Ok(None) | Err(_) => {
                debug!("[gsm] Unable to fetch GSM MCC");
                time::sleep(Duration::from_secs(3600 * 24)).await;
                continue;
            }
        };
        // TODO lookup MCC to coords

        info!("[gsm] MCC: {}", mcc);
        let up = Update {
            plocation: NOWHERE,
            extra: None,
            src_kind: SrcKind::Gnss,
            last_update_time: Instant::now(),
        };
        chan.send(up).await.unwrap();
        time::sleep(Duration::from_secs(60 * 30)).await;
    }
}

// ----- WiFi/Bluetooth/GSM -----

/// Scan for WiFi devices around
async fn scan_wifi() -> Result<Blips> {
    debug!("[wifi_bt] running nmcli");
    let output = tokio::process::Command::new("nmcli")
        .args([
            "--fields",
            "SSID-HEX,BSSID,CHAN,SIGNAL,SECURITY",
            "--colors",
            "no",
            "--escape",
            "no",
            "device",
            "wifi",
            "list",
        ])
        .output()
        .await
        .context("Failed to execute nmcli")?;

    if !output.status.success() {
        info!("[wifi_bt] nmcli failed");
        anyhow::bail!("nmcli command failed");
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<&str> = stdout.lines().collect();

    let mut blips: Blips = vec![];
    // Skip header line
    for line in lines {
        let columns: Vec<&str> = line.split_whitespace().collect();
        if columns.len() >= 5 {
            let hex_ssid = columns[0];
            if hex_ssid == "SSID-HEX" {
                continue;
            }
            let macaddr = columns[1];
            let channel = columns[2];
            let signal = columns[3];
            let security = columns[4];

            let bytes = match Vec::from_hex(hex_ssid) {
                Ok(v) => v,
                Err(_) => continue,
            };
            debug!("[wifi_bt] converting {macaddr} {signal} {security} {hex_ssid}");
            let ssid = String::from_utf8_lossy(&bytes).into_owned();
            // debug!("converting {macaddr} {signal} {security} {ssid}");

            // TODO Blips as a struct
            let macaddr = match parse_macaddr(macaddr) {
                Ok(v) => v,
                Err(_) => continue,
            };
            // debug!("converted {signal} {security} {ssid}");
            blips.push((Coord { x: 0., y: 0. }, macaddr, ssid));
        }
    }

    Ok(blips)
}

/// Locate using WiFi
async fn wifi_bt_location_fetcher(chan: tokio::sync::mpsc::Sender<Update>, url: String) {
    loop {
        info!("[wifi_bt] scan and locate cycle started");
        if let Ok(blips) = scan_wifi().await {
            info!("[wifi_bt] {} nearby devices detected", blips.len());
            if let Ok(plocation) = geolocate_blips(&url, blips).await {
                let up = Update {
                    plocation,
                    extra: None,
                    src_kind: SrcKind::WifiBt,
                    last_update_time: Instant::now(),
                };
                chan.send(up).await.unwrap();
            } else {
                info!("[wifi_bt] failed to geolocate WiFi emitters");
            }
        } else {
            info!("[wifi_bt] failed to scan for WiFi emitters");
        };

        time::sleep(Duration::from_secs(2)).await;
    }
}

/// Estimate rough accuracy from older location based on their age.
/// E.g. if it's from 1 hour ago the device is likely to be within kms
/// and cannot be on the opposite side of the Earth.
fn calc_accuracy_from_last_plocation(pl: &Plocation, past: SystemTime) -> Plocation {
    const KPH: f32 = 200.;
    if let Ok(delta) = SystemTime::now().duration_since(past) {
        let hours = delta.as_secs() as f32 / 3600.;
        let lsm = pl.lsm * hours * KPH;
        Plocation { loc: pl.loc, lsm }
    } else {
        NOWHERE
    }
}

fn spawn_workers(conf: Conf, tx: Sender) {
    {
        let tx = tx.clone();
        tokio::spawn(gnss_reader(tx));
    }
    {
        let tx = tx.clone();
        tokio::spawn(geoip_prober(tx));
    }
    {
        let tx = tx.clone();
        tokio::spawn(gsm_country_code_reader(tx));
    }
    {
        let tx = tx.clone();
        let url = conf.fetch_url.clone().unwrap().clone();
        tokio::spawn(wifi_bt_location_fetcher(tx, url));
    }
}

/// Libreloc client
#[derive(structopt::StructOpt, Debug)]
#[structopt(name = "libreloc_client")]
enum Cli {
    /// Updates description for an existing device.
    UploadCSV {
        /// CSV filename
        #[structopt(parse(from_os_str))]
        filename: std::path::PathBuf,
    },
    /// Locate the client
    Locate,
    /// Locate the client using WiFi data from CSV
    LocateCSV {
        /// File name
        #[structopt(parse(from_os_str))]
        filename: std::path::PathBuf,
    },
    /// Run the client
    Run,
    UploadRandomDataBench,
}

async fn receive_updates_until_exit(
    mut rx: Receiver,
    location_state: Arc<Mutex<HashMap<SrcKind, Source>>>,
    global_loc: Arc<Mutex<Plocation>>,
) -> Result<()> {
    while let Some(update) = rx.recv().await {
        // Receive an update, store it and fuse the locations
        // Share status with the MLS API and dashboard
        let mut location_state = location_state.lock().unwrap();
        let s = location_state.get_mut(&update.src_kind).unwrap();
        s.last_plocation = update.plocation;
        s.last_update_time = update.last_update_time;
        info!("[main] fusing {:?}", &s);
        let locs = location_state.values().map(|s| s.last_plocation).collect();
        let mut g = global_loc.lock().unwrap();
        let loc = fuse_location_sources(locs);
        g.loc = loc.loc;
        g.lsm = loc.lsm;
        info!("[main] Location: {:?}", g);
    }
    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli_cmd: Cli = Cli::from_args();
    // Setup logging
    if let Cli::Run = cli_cmd {
        JournalLog::new()?.install()?;
    } else {
        simple_logger::SimpleLogger::new()
            .with_module_level("rewqest", LevelFilter::Warn)
            .init()?;
    }
    log::set_max_level(LevelFilter::Debug);
    info!("[main] starting");
    // Read conf
    let conf = load_conf().unwrap_or_else(|err| {
        error!("{}", err);
        std::process::exit(1)
    });

    let args = Cli::from_args();
    match args {
        Cli::UploadCSV { filename } => upload_csv(&conf, &filename).await?,
        Cli::LocateCSV { filename } => locate_from_csv(&conf, &filename).await?,
        Cli::Locate => locate_from_cli(&conf).await?,
        Cli::Run => {}
        Cli::UploadRandomDataBench => upload_random_data_bench(&conf).await?,
    }
    if let Cli::Run = cli_cmd {
    } else {
        return Ok(());
    }

    let app_state = AppState {
        conf: conf.clone(),
        location_state: Arc::new(Mutex::new(HashMap::new())),
        location: Arc::new(Mutex::new(NOWHERE)),
    };

    {
        let mut location_state = app_state.location_state.lock().unwrap();
        let vals = &[SrcKind::Gnss, SrcKind::GsmCountry, SrcKind::WifiBt];
        for v in vals {
            location_state.insert(
                v.clone(),
                Source {
                    name: format!("{:?}", v.clone()),
                    last_plocation: NOWHERE,
                    last_update_time: Instant::now(),
                },
            );
        }
    }
    let location_state = app_state.location_state.clone();
    let gloc = app_state.location.clone();

    tokio::spawn(run_location_service_api(conf.clone(), app_state));

    let (tx, rx) = mpsc::channel(10);
    spawn_workers(conf.clone(), tx);

    // TODO: wake up workers when the OS wakes up from sleep
    // TODO: tune workers speed dynamically

    receive_updates_until_exit(rx, location_state, gloc).await?;
    Ok(())
}

/// Remote lookup with caching
pub async fn cached_remote_lookup(
    reqc: &reqwest::Client,
    baseurl: &str,
    geopath: &str,
    blips: &Blips,
    stats: &mut CacheStats,
) -> Result<(f32, String)> {
    let cache = Cache::new().await?;

    let mut blooms: Vec<BloomHash> = Vec::new();
    for (_, mac, ssid) in blips {
        // debug!("[lookup] lookup SSID {ssid}");
        let fingerprint = generate_fingerprint_wifi(geopath, mac, ssid);
        let url = format!("{}/{}", baseurl, fingerprint);
        // debug!("[lookup] lookup {url}");
        stats.tot_cnt += 1;
        let bloom: BloomHash = {
            if let Some(blob) = cache.read_data(&fingerprint).await {
                ensure!(blob.len() == 128);
                let array: [u8; 128] = blob.try_into().unwrap();
                stats.hit_cnt += 1;
                BloomHash::new(array)
            } else {
                // TODO retries, handle failures
                let resp = reqc.get(url).send().await?;
                ensure!(resp.status().is_success());
                // resp.error_for_status()?;
                let bytes = resp.bytes().await?;
                ensure!(bytes.len() == 128);
                cache.store_data(&fingerprint, &bytes).await?;
                let array: [u8; 128] = bytes.as_ref().try_into()?;
                BloomHash::new(array)
            }
        };
        blooms.push(bloom);
    }

    let (selectiveness, b) = pick_best_segment(pile_up_blooms(blooms));
    Ok((selectiveness, geosegment_to_string(b)))
}

pub struct CacheStats {
    hit_cnt: i32,
    tot_cnt: i32,
}

async fn locate_from_csv(conf: &Conf, fname: &PathBuf) -> Result<()> {
    ensure!(conf.fetch_url.is_some(), "Data fetch URL not configured");

    // Load CSV file into blips
    let file = std::fs::File::open(fname)?;
    let mut rdr = csv::ReaderBuilder::new().from_reader(file);
    let mut blips: Blips = vec![];
    for result in rdr.deserialize() {
        let r: NeoStumblerCsvRow = result?;
        blips.push((
            Coord {
                x: r.longitude.parse()?,
                y: r.latitude.parse()?,
            },
            parse_macaddr(&r.macAddress)?,
            r.ssid,
        ));
    }

    let url = conf.fetch_url.clone().unwrap();
    geolocate_blips(&url, blips).await?;

    Ok(())
}

/// Geolocate blips using remote server and caching
async fn geolocate_blips(url: &str, blips: Vec<(Coord, [u8; 6], String)>) -> Result<Plocation> {
    let mut stats = CacheStats {
        hit_cnt: 0,
        tot_cnt: 0,
    };
    let reqc = reqwest::Client::new();
    let mut geopath = "".to_string();
    for step in 0..4 {
        debug!("[lookup] step n. {step}");
        let (sel, segment) =
            cached_remote_lookup(&reqc, &url, &geopath, &blips, &mut stats).await?;
        geopath.push_str(&segment);
        info!(
            "[lookup] [{} {}] https://geohash.jorren.nl/#{}",
            step, sel, geopath
        );
        debug!(
            "[lookup] Cacheing efficiency: {}%",
            stats.hit_cnt * 100 / stats.tot_cnt
        )
    }
    geohash_to_plocation(&geopath)
}

async fn locate_from_cli(conf: &Conf) -> Result<()> {
    todo!();
    Ok(())
}

// timestamp,latitude,longitude,locationAccuracy,locationAge,speed,macAddress,wifiScanAge,signalStrength,ssid

#[allow(non_snake_case)]
#[derive(Debug, serde::Deserialize, Eq, PartialEq)]
struct NeoStumblerCsvRow {
    timestamp: String,
    latitude: String,
    longitude: String,
    locationAccuracy: String,
    locationAge: String,
    speed: String,
    macAddress: String,
    wifiScanAge: String,
    signalStrength: String,
    ssid: String,
}

/// Read CSV and insert values into a BloomHashStore
fn load_csv(fname: &PathBuf) -> Result<BloomHashStore> {
    let file = std::fs::File::open(fname)?;
    let mut rdr = csv::ReaderBuilder::new().from_reader(file);
    let mut bhs = BloomHashStore::new();
    for result in rdr.deserialize() {
        let r: NeoStumblerCsvRow = result?;
        bhs.insert_datapoint(
            r.latitude.parse()?,
            r.longitude.parse()?,
            &parse_macaddr(&r.macAddress)?,
            &r.ssid,
        );
    }
    debug!("Stats {:?}", bhs.stats());
    Ok(bhs)
}

/// Upload datapoints to server
async fn upload_csv(conf: &Conf, fname: &PathBuf) -> Result<()> {
    ensure!(conf.upload_url.is_some(), "Upload URL not configured");

    // Pack and upload
    let bhs = load_csv(fname)?;
    let blob = bhs.pack_then_compress()?;
    info!("[upload-csv] Compressed blob size {:?}", blob.len());
    let reqc = reqwest::Client::new();
    let resp = reqc
        .post(conf.upload_url.as_ref().unwrap())
        .body(blob)
        .send()
        .await?;
    resp.error_for_status()?;
    info!("[upload-csv] done");
    Ok(())
}

/// Upload random data
async fn upload_random_data_bench(conf: &Conf) -> Result<()> {
    ensure!(conf.upload_url.is_some(), "Upload URL not configured");
    let mut rng: StdRng = SeedableRng::seed_from_u64(3);

    // Pack and upload
    for _ in 0..1000 {
        let mut bhs = BloomHashStore::new();
        for _ in 0..10_000 {
            let lat = rng.gen_range(-90.0..=90.0);
            let lon = rng.gen_range(-180.0..=180.0);
            let mac: Mac = rng.gen();
            let ssid = Alphanumeric.sample_string(&mut rng, 16);
            bhs.insert_datapoint(lat, lon, &mac, &ssid)
        }
        let blob = bhs.pack_then_compress()?;
        info!("[upload-bench] Compressed blob size {:?}", blob.len());
        let reqc = reqwest::Client::new();
        let resp = reqc
            .post(conf.upload_url.as_ref().unwrap())
            .body(blob)
            .send()
            .await?;
        resp.error_for_status()?;
    }
    info!("[upload-bench] done");
    Ok(())
}

// ----- cache management -----

struct Cache {
    cachedir: PathBuf,
}

impl Cache {
    /// Pick cache directory creating it if needed
    async fn new() -> Result<Self> {
        let xdg_dirs = xdg::BaseDirectories::with_prefix("libreloc_client")?;
        let cachedir = xdg_dirs.create_cache_directory("cache")?;
        Ok(Cache { cachedir })
    }

    async fn prune_old_files(&self, max_age: Duration) -> Result<()> {
        let now = SystemTime::now();
        let mut fnames = fs::read_dir(&self.cachedir).await?;
        loop {
            let file = fnames.next_entry().await?;
            if let Some(f) = file {
                let mtime = f.metadata().await?.modified()?;
                if now.duration_since(mtime).unwrap_or_default() > max_age {
                    debug!("[cache] deleting {}", f.path().to_string_lossy());
                    fs::remove_file(f.path()).await?;
                }
            } else {
                return Ok(());
            }
        }
    }

    fn file_path(&self, key: &str) -> PathBuf {
        self.cachedir.join(format!("cache_{}", key))
    }

    /// Write out cache file for a given key
    async fn store_data(&self, key: &str, data: &Bytes) -> Result<()> {
        // FIXME implement atomic write
        let fname = self.file_path(key);
        let mut file = fs::File::create(&fname)
            .await
            .with_context(|| format!("Failed to create {:?}", fname))?;
        file.write_all(data)
            .await
            .with_context(|| format!("Failed to write to {:?}", fname))?;

        Ok(())
    }

    async fn read_data(&self, key: &str) -> Option<Vec<u8>> {
        let fname = self.file_path(key);
        let file = fs::File::open(&fname).await;
        if let Ok(mut file) = file {
            let mut data = Vec::new();
            file.read_to_end(&mut data).await.unwrap();
            Some(data)
        } else {
            None
        }
    }
}

// ----- Built-in user-facing API including MLS server -----

async fn upload_geosubmit(conf: &Conf, msg: MLSGeoSubmit) -> Result<()> {
    ensure!(conf.upload_url.is_some(), "Upload URL not configured");
    let mut bhs = BloomHashStore::new();

    for i in msg.items {
        info!("[api-sub] {:?} {:?}", i.timestamp, i.position);

        let Some(p) = i.position else { continue };

        for aps in i.wifiAccessPoints {
            for ap in aps {
                bhs.insert_datapoint(
                    p.latitude,
                    p.longitude,
                    &parse_macaddr(&ap.macAddress)?,
                    &ap.ssid.unwrap_or("".to_owned()),
                );
            }
        }
    }
    debug!("[api-sub] {:?}", bhs.stats());
    let blob = bhs.pack_then_compress()?;
    info!("[api-sub] Compressed blob size {:?}", blob.len());
    let reqc = reqwest::Client::new();
    let resp = reqc
        .post(conf.upload_url.as_ref().unwrap())
        .body(blob)
        .send()
        .await?;
    resp.error_for_status()?;
    Ok(())
}

// --- routes ---

/// Receives a /v2/geosubmit POST and upload the WiFi data to a Libreloc server
async fn post_mls_geosubmit(
    State(app_state): State<AppState>,
    axum::extract::Json(msg): axum::extract::Json<MLSGeoSubmit>,
) -> impl IntoResponse {
    info!("[api-sub] geosubmit received");
    if let Err(e) = upload_geosubmit(&app_state.conf, msg).await {
        info!("[api-sub] error {}", e);
        StatusCode::SERVICE_UNAVAILABLE
    } else {
        info!("[api-sub] done");
        StatusCode::OK
    }
}

/// Serve basic statistics
async fn get_stats() -> impl IntoResponse {
    debug!("GET stats");
    let j = serde_json::json!({
        "component": "client",
    });
    (StatusCode::OK, axum::Json(j))
}

// ----- HTML dashboard -----

struct DashRow {
    status: String,
    name: String,
}

/// Dashboard
#[derive(TemplateOnce)]
#[template(path = "dashboard.stpl")]
struct DashTemplate<'a> {
    dash_tbl: Vec<&'a Source>,
    tstamp: &'a str,
    js_blob: &'a str,
}

/// Serve dashboard
async fn serve_http_get_dashboard(
    State(app_state): State<AppState>,
) -> axum::response::Html<String> {
    let js_blob = include_str!("../templates/dashboard.js");
    debug!("GET dashboard");
    let location_state = app_state.location_state.lock().unwrap();
    let dash_tbl = location_state.values().collect();
    let tstamp = "".into();
    let tpl = DashTemplate {
        dash_tbl,
        tstamp,
        js_blob,
    };
    axum::response::Html(tpl.render_once().unwrap())
}

/// Serve location
async fn serve_http_get_location(State(app_state): State<AppState>) -> impl IntoResponse {
    debug!("GET /v2/location");
    let loc = app_state.location.lock().unwrap();
    let j = serde_json::json!({
        "lat": loc.loc.y,
        "lon": loc.loc.x,
        "r": loc.lsm * 100.,
    });
    (StatusCode::OK, axum::Json(j))
}

/// Run a local HTTP service to provide MLS-compatible location, geosubmit, a UI,
/// stats etc
async fn run_location_service_api(conf: Conf, app_state: AppState) -> Result<()> {
    let addr: std::net::SocketAddr = conf
        .listen_addr
        .clone()
        .unwrap_or("127.0.0.1:3939".to_owned())
        .parse()?;

    let app: Router = Router::new()
        .route("/", get(get_stats))
        .route("/v2/ui", get(serve_http_get_dashboard))
        .route("/v2/location", get(serve_http_get_location))
        .route("/v2/geosubmit", post(post_mls_geosubmit))
        .layer(
            tower::ServiceBuilder::new()
                .layer(tower_http::decompression::RequestDecompressionLayer::new()),
        )
        .with_state(app_state);
    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    info!("[api] starting at addr {:?}", addr);
    axum::serve(listener, app).await.unwrap();
    Ok(())
}