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
use std::{collections::HashMap, rc::Rc};

use content_inspector::inspect;
use handlebars::Handlebars;
use serde::Serialize;

use crate::{
    config::DTConfig,
    error::{Error as AppError, Result},
};

#[allow(unused_variables)]
/// A registry should hold an environment of templates, and a cached storing
/// the rendered contents.
pub trait Register
where
    Self: Sized,
{
    /// Registers DT's [built-in helpers].
    ///
    /// [built-in helpers]: helpers
    fn register_helpers(self) -> Result<Self> {
        unimplemented!()
    }
    /// Load templates and render them into cached storage, items that are not
    /// templated (see [`is_templated`]) will not be registered into templates
    /// but directly stored into the rendered cache.
    ///
    /// [`is_templated`]: crate::config::Group::is_templated
    fn load(self, config: &DTConfig) -> Result<Self> {
        unimplemented!()
    }
    /// Returns the content of an item rendered with given rendering context.
    /// This does not modify the stored content.
    ///
    /// Rendering only happens if this item is considered as a plain text
    /// file.  If this item is considered as a binary file, it's original
    /// content is returned.  The content type is inspected via the
    /// [`content_inspector`] crate.  Although it can correctly determine if
    /// an item is binary or text mostly of the time, it is just a heuristic
    /// check and can fail in some cases, e.g. NUL byte in the first 1024
    /// bytes of a UTF-8-encoded text file, etc..  See [the crate's home page]
    /// for the full caveats.
    ///
    /// [`content_inspector`]: https://crates.io/crates/content_inspector
    /// [the crate's home page]: https://github.com/sharkdp/content_inspector
    fn render<S: Serialize>(
        &self,
        name: &str,
        ctx: &Rc<S>,
    ) -> Result<Vec<u8>> {
        unimplemented!()
    }
    /// Updates the stored content of an item with the new content rendered
    /// with given rendering context.
    fn update<S: Serialize>(
        &mut self,
        name: &str,
        ctx: &Rc<S>,
    ) -> Result<()> {
        unimplemented!()
    }
    /// Looks up the rendered content of an item with given name.
    fn get(&self, name: &str) -> Result<Vec<u8>> {
        unimplemented!()
    }
}

/// Registry with a cache for rendered item contents.
#[derive(Debug, Default)]
pub struct Registry<'reg> {
    /// The templates before rendering.
    pub env: Handlebars<'reg>,
    /// The rendered contents of items.
    pub content: HashMap<String, Vec<u8>>,
}

impl Register for Registry<'_> {
    fn register_helpers(self) -> Result<Self> {
        let mut render_env = self.env;

        render_env.register_helper("get_mine", Box::new(helpers::get_mine));
        render_env.register_helper("for_user", Box::new(helpers::for_user));
        render_env.register_helper("for_uid", Box::new(helpers::for_uid));
        render_env.register_helper("for_host", Box::new(helpers::for_host));

        Ok(Self {
            env: render_env,
            ..self
        })
    }

    fn load(self, config: &DTConfig) -> Result<Self> {
        let mut registry = self;
        for group in &config.local {
            for s in &group.sources {
                let name = s.to_string_lossy();
                if let Ok(content) = std::fs::read(s) {
                    if group.is_templated() {
                        if inspect(&content).is_text() {
                            registry.env.register_template_string(
                                &name,
                                std::str::from_utf8(&content)?,
                            )?;
                            registry.content.insert(
                                name.to_string(),
                                registry
                                    .env
                                    .render(&name, &config.context)?
                                    .into(),
                            );
                        } else {
                            log::trace!(
                                "'{}' will not be rendered because it has binary contents",
                                s.display(),
                            );
                            registry
                                .content
                                .insert(name.to_string(), content);
                        }
                    } else {
                        log::trace!(
                            "'{}' will not be rendered because it is not templated",
                            s.display(),
                        );
                        registry.content.insert(name.to_string(), content);
                    }
                }
            }
        }
        Ok(registry)
    }

    fn render<S: Serialize>(
        &self,
        name: &str,
        ctx: &Rc<S>,
    ) -> Result<Vec<u8>> {
        if self.env.get_template(name).is_some() {
            Ok(self.env.render(name, &**ctx)?.into())
        } else {
            match self.content.get(name) {
                Some(content) => Ok(content.to_owned()),
                None => Err(AppError::RenderingError(format!(
                    "The template specified by '{}' is not known",
                    name,
                ))),
            }
        }
    }

    fn update<S: Serialize>(
        &mut self,
        name: &str,
        ctx: &Rc<S>,
    ) -> Result<()> {
        self.content
            .insert(name.to_owned(), self.render(name, ctx)?);
        Ok(())
    }

    fn get(&self, name: &str) -> Result<Vec<u8>> {
        match self.content.get(name) {
            Some(content) => Ok(content.to_owned()),
            None => Err(AppError::TemplatingError(format!(
                "The template specified by '{}' is not known",
                name,
            ))),
        }
    }
}

// ===========================================================================

/// Additional built-in helpers
pub mod helpers {
    use gethostname::gethostname;
    use handlebars::{
        Context, Handlebars, Helper, HelperResult, JsonRender, Output,
        RenderContext, RenderError, Renderable,
    };
    use users::{get_current_uid, get_current_username};

    /// A templating helper that retrieves the value for current host from a
    /// map, returns a default value when current host is not recorded in the
    /// map.
    ///
    /// Usage:
    ///
    /// 1. `{{ get_mine }}`
    ///
    ///     Renders current machine's hostname.
    /// 2. `{{ get_mine <map> <default-value> }}`
    ///
    ///     Renders `<map>.$CURRENT_HOSTNAME`, falls back to `<default-value>`.
    pub fn get_mine(
        h: &Helper,
        _: &Handlebars,
        _: &Context,
        _rc: &mut RenderContext,
        out: &mut dyn Output,
    ) -> HelperResult {
        let map = match h.param(0) {
            Some(map) => map.value(),
            None => {
                out.write(&gethostname().to_string_lossy())?;
                return Ok(());
            }
        };
        let default_content = match h.param(1) {
            Some(content) => content.value(),
            None => {
                return Err(RenderError::new(&format!(
                    r#"
Inline helper `{0}`:
    expected 0 or 2 arguments, 1 found

    Usage:
        1. {{{{ {0} }}}}
            (Renders current machine's hostname)

        2. {{{{ {0} <map> <default-value> }}}}
            (Gets value of <map>.$CURRENT_HOSTNAME, falls back to <default-value>)"#,
                    h.name(),
                )))
            }
        };

        let content =
            match map.get(gethostname().to_string_lossy().to_string()) {
                Some(content) => content.render(),
                None => default_content.render(),
            };

        out.write(&content)?;

        Ok(())
    }

    /// A templating helper that tests if current user's username matches a
    /// given string.
    ///
    /// Usage:
    ///
    /// 1. `{{#for_user "foo"}}..content..{{/for_user}}`
    ///
    ///     Renders content only if current user's username is "foo".
    /// 2. `{{#for_user "foo"}}{{else}}..content..{{/for_user}}`
    ///
    ///     Renders content only if current user's username is NOT "foo".
    pub fn for_user<'reg, 'rc>(
        h: &Helper<'reg, 'rc>,
        r: &'reg Handlebars<'reg>,
        ctx: &'rc Context,
        rc: &mut RenderContext<'reg, 'rc>,
        out: &mut dyn Output,
    ) -> HelperResult {
        if h.params().len() > 1 {
            return Err(RenderError::new(&format!(
                r#"
Block helper `#{0}`:
    expected exactly 1 argument, {1} found

    Usage:
        1. {{{{#{0} "foo"}}}}..content..{{{{/{0}}}}}
                (Renders `..content..` only if current user's username is "foo")

        2. {{{{#{0} "foo"}}}}{{{{else}}}}..content..{{{{/{0}}}}}
                (Renders `..content..` only if current user's username is NOT "foo")
                    "#,
                h.name(),
                h.params().len(),
            )));
        }

        let username: String = match h.param(0) {
            Some(v) => v.value().render(),
            None => {
                return Err(RenderError::new(&format!(
                    r#"
Block helper `#{0}`:
    expected exactly 1 argument, 0 found

    Usage:
        1. {{{{#{0} "foo"}}}}..content..{{{{/{0}}}}}
                (Renders `..content..` only if current user's username is "foo")

        2. {{{{#{0} "foo"}}}}{{{{else}}}}..content..{{{{/{0}}}}}
                (Renders `..content..` only if current user's username is NOT "foo")
                    "#,
                    h.name(),
                )));
            }
        };

        let current_username = get_current_username()
            .unwrap()
            .to_string_lossy()
            .to_string();
        if current_username == username {
            log::debug!(
                "Current username {} matches {}",
                current_username,
                username,
            );
            h.template().map(|t| t.render(r, ctx, rc, out));
        } else {
            log::debug!(
                "Current username {} is not {}",
                current_username,
                username,
            );
            h.inverse().map(|t| t.render(r, ctx, rc, out));
        }
        Ok(())
    }

    /// A templating helper that tests if current user's effective uid matches
    /// a given integer.
    ///
    /// Usage:
    ///
    /// 1. `{{#for_uid 0}}..content..{{/for_uid}}`
    ///
    ///     Renders `..content..` only if current user's effective uid is 0.
    /// 2. `{{#for_uid 0}}{{else}}..content..{{/for_uid}}`
    ///
    ///     Renders `..content..` only if current user's effective uid is NOT 0.
    pub fn for_uid<'reg, 'rc>(
        h: &Helper<'reg, 'rc>,
        r: &'reg Handlebars<'reg>,
        ctx: &'rc Context,
        rc: &mut RenderContext<'reg, 'rc>,
        out: &mut dyn Output,
    ) -> HelperResult {
        if h.params().len() > 1 {
            return Err(RenderError::new(&format!(
                r#"
Block helper `#{0}`:
    expected exactly 1 argument, {1} found

    Usage:
        1. {{{{#{0} 0}}}}..content..{{{{/{0}}}}}
            (Renders `..content..` only if current user's effective uid is 0)

        2. {{{{#{0} 0}}}}{{{{else}}}}..content..{{{{/{0}}}}}
            (Renders `..content..` only if current user's effective uid is NOT 0)
                    "#,
                h.name(),
                h.params().len(),
            )));
        }

        let uid: u32 = match h.param(0) {
            Some(v) => v.value().render().parse()?,
            None => {
                return Err(RenderError::new(&format!(
                    r#"
Block helper `#{0}`:
    expected exactly 1 argument, 0 found

    Usage:
        1. {{{{#{0} 0}}}}..content..{{{{/{0}}}}}
            (Renders `..content..` only if current user's effective uid is 0)

        2. {{{{#{0} 0}}}}{{{{else}}}}..content..{{{{/{0}}}}}
            (Renders `..content..` only if current user's effective uid is NOT 0)
                    "#,
                    h.name(),
                )));
            }
        };

        let current_uid = get_current_uid();
        if current_uid == uid {
            log::debug!("Current uid '{}' matches '{}'", current_uid, uid);
            h.template().map(|t| t.render(r, ctx, rc, out));
        } else {
            log::debug!("Current uid '{}' is not '{}'", current_uid, uid);
            h.inverse().map(|t| t.render(r, ctx, rc, out));
        }
        Ok(())
    }

    /// A templating helper that tests if current machine's hostname matches a
    /// given string.
    ///
    /// Usage:
    ///
    /// 1. `{{#for_host "bar"}}..content..{{/for_host}}`
    ///
    ///     Renders content only if current machine's hostname is "bar".
    /// 2. `{{#for_host "bar"}}{{else}}..content..{{/for_host}}`
    ///
    ///     Renders content only if current machine's hostname is NOT "bar".
    pub fn for_host<'reg, 'rc>(
        h: &Helper<'reg, 'rc>,
        r: &'reg Handlebars<'reg>,
        ctx: &'rc Context,
        rc: &mut RenderContext<'reg, 'rc>,
        out: &mut dyn Output,
    ) -> HelperResult {
        if h.params().len() > 1 {
            return Err(RenderError::new(&format!(
                r#"
Block helper `#{0}`:
    expected exactly 1 argument, {1} found

    Usage:
        1. {{{{#{0} "bar"}}}}..content..{{{{/{0}}}}}
                (Renders `..content..` only if current machine's hostname is "bar")

        2. {{{{#{0} "bar"}}}}{{{{else}}}}..content..{{{{/{0}}}}}
                (Renders `..content..` only if current machine's hostname is NOT "bar")
                    "#,
                h.name(),
                h.params().len(),
            )));
        }

        let expected_hostname: String = match h.param(0) {
            Some(v) => v.value().render(),
            None => {
                return Err(RenderError::new(&format!(
                    r#"
Block helper `#{0}`:
    expected exactly 1 argument, 0 found

    Usage:
        1. {{{{#{0} "bar"}}}}..content..{{{{/{0}}}}}
                (Renders `..content..` only if current machine's hostname is "bar")

        2. {{{{#{0} "bar"}}}}{{{{else}}}}..content..{{{{/{0}}}}}
                (Renders `..content..` only if current machine's hostname is NOT "bar")
                    "#,
                    h.name(),
                )));
            }
        };

        let current_hostname = gethostname();
        let current_hostname = current_hostname.to_string_lossy();
        if current_hostname == expected_hostname {
            log::debug!(
                "Current hostname {} matches {}",
                current_hostname,
                expected_hostname,
            );
            h.template().map(|t| t.render(r, ctx, rc, out));
        } else {
            log::debug!(
                "Current hostname {} is not {}",
                current_hostname,
                expected_hostname,
            );
            h.inverse().map(|t| t.render(r, ctx, rc, out));
        }
        Ok(())
    }
}

// Author: Blurgy <gy@blurgy.xyz>
// Date:   Jan 29 2022, 14:42 [CST]