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
use std::collections::HashMap;
use std::fmt::{self, Display};
use std::sync::Arc;

use crate::config::{
    CliOptions, CustomExtensions, ExtensionBundles, HostCollections, Hosts, Result,
};
use kvarn::prelude::{CompactString, ToCompactString};
use log::info;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum HostSource {
    Collection(String),
    Hosts(Vec<String>),
    Host(String),
    All,
}
impl HostSource {
    pub async fn resolve(
        self,
        host_collections: &HostCollections,
        hosts: &Hosts,
        exts: &ExtensionBundles,
        custom_exts: &CustomExtensions,
        opts: &CliOptions<'_>,
    ) -> Result<Arc<kvarn::host::Collection>> {
        match self {
            HostSource::Collection(name) => host_collections
                .get(name.as_str())
                .cloned()
                .ok_or_else(|| format!("Didn't find a host collection with name {name}.")),
            HostSource::Hosts(source) => {
                let collection = crate::config::construct_collection(
                    source.into_iter().map(CompactString::from).collect(),
                    hosts,
                    exts,
                    custom_exts,
                    opts,
                )
                .await?;
                Ok(collection)
            }
            HostSource::Host(source) => {
                let collection = crate::config::construct_collection(
                    vec![source.to_compact_string()],
                    hosts,
                    exts,
                    custom_exts,
                    opts,
                )
                .await?;
                Ok(collection)
            }
            HostSource::All => {
                let collection = crate::config::construct_collection(
                    hosts.keys().cloned().collect(),
                    hosts,
                    exts,
                    custom_exts,
                    opts,
                )
                .await?;
                Ok(collection)
            }
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PortMapEntry {
    encrypted: bool,
    source: HostSource,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum PortsKind {
    Map(HashMap<u16, PortMapEntry>),
    Standard(HostSource),
    HttpsOnly(HostSource),
    HttpOnly(HostSource),
}
impl PortsKind {
    pub async fn resolve(
        self,
        host_collections: &HostCollections,
        hosts: &Hosts,
        exts: &ExtensionBundles,
        custom_exts: &CustomExtensions,
        opts: &CliOptions<'_>,
    ) -> Result<Vec<kvarn::PortDescriptor>> {
        enum NPorts<'a> {
            One(u16),
            Several(&'a [u16]),
        }
        impl<'a> Display for NPorts<'a> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                match self {
                    NPorts::One(port) => write!(f, "port {port}"),

                    NPorts::Several(v) => {
                        write!(f, "ports ")?;
                        for port in v.get(0..v.len() - 1).unwrap_or(&[]) {
                            write!(f, "{port}, ")?;
                        }
                        if let Some(port) = v.last() {
                            write!(f, "{port}")?;
                        }
                        Ok(())
                    }
                }
            }
        }
        let log_bind = |source: &HostSource, port: NPorts| {
            match source {
                HostSource::Collection(name) => {
                    info!("Bind host collection \"{name}\" to {port}")
                }
                HostSource::Hosts(hosts) => info!("Bind hosts {hosts:?} to {port}"),
                HostSource::Host(host) => info!("Bind host collection \"{host}\" to {port}"),
                HostSource::All => info!("Binding all hosts to {port}"),
            };
        };

        match self {
            PortsKind::Map(map) => {
                let mut v = Vec::with_capacity(map.len());
                for (port, entry) in map {
                    log_bind(&entry.source, NPorts::One(port));
                    let descriptor = if entry.encrypted {
                        kvarn::PortDescriptor::new(
                            port,
                            entry
                                .source
                                .resolve(host_collections, hosts, exts, custom_exts, opts)
                                .await?,
                        )
                    } else {
                        kvarn::PortDescriptor::unsecure(
                            port,
                            entry
                                .source
                                .resolve(host_collections, hosts, exts, custom_exts, opts)
                                .await?,
                        )
                    };
                    v.push(descriptor);
                }
                Ok(v)
            }
            PortsKind::Standard(source) => {
                let ports = if opts.high_ports {
                    &[8080, 8443]
                } else {
                    &[80, 443]
                };
                log_bind(&source, NPorts::Several(ports));

                let collection = source
                    .resolve(host_collections, hosts, exts, custom_exts, opts)
                    .await?;
                let v = vec![
                    kvarn::PortDescriptor::unsecure(ports[0], collection.clone()),
                    kvarn::PortDescriptor::new(ports[1], collection),
                ];
                Ok(v)
            }
            PortsKind::HttpsOnly(source) => {
                let port = if opts.high_ports { 8443 } else { 443 };
                log_bind(&source, NPorts::One(port));

                let collection = source
                    .resolve(host_collections, hosts, exts, custom_exts, opts)
                    .await?;
                let v = vec![kvarn::PortDescriptor::new(port, collection)];
                Ok(v)
            }
            PortsKind::HttpOnly(source) => {
                let port = if opts.high_ports { 8080 } else { 80 };
                log_bind(&source, NPorts::One(port));

                let collection = source
                    .resolve(host_collections, hosts, exts, custom_exts, opts)
                    .await?;
                let v = vec![kvarn::PortDescriptor::unsecure(port, collection)];
                Ok(v)
            }
        }
    }
}