<%
  /*
    This is broken too, adds an unnecessary "undefine" to output.
  */

  var
    generateSitemapXML = function(the_head, the_tail, the_base) {
      var
        filter = /(\.html$)/,
        replace = /(\.html$)|(^index\.html$)/,
        tree = function (head, tail, base) {
          var
            output = '',
            tree_output = '',
            data, content;
          for (var key in head) {
            var
              val = head[key];
            if (key && val && key !== '.git') {
              if (key == '_data') {
                data = val;
              } else if (key == '_contents') {
                content = val;
              } else {
                tree_output += tree(val, tail + key + "/", base);
              }
            }
          }

          if (content) {
            for (var i in content) {
              var
                file = content[i],
                slug = file.replace(filter, ""),
                file_data = data && data[slug] ? data[slug] : {},
                now = new Date(),
                show_item = false,
                upd_date;
              if (filter.test(file)) {
                show_item = true;
                if (file_data) {
                  var
                    is_draft = file_data.is_draft || false,
                    is_sys_file = file_data.is_sys_file || false,
                    title = (file_data.title || '').trim();
                  if (is_draft || is_sys_file || title === '') {
                    show_item = false;
                  } else {
                    upd_date = file_data.date_last_mod ? new Date(file_data.date_last_mod) : '';
                    upd_date = upd_date !== '' && file_data.date_pub ? new Date(file_data.date_pub) : '';
                    if ((upd_date && upd_date.getTime() > now.getTime())) {
                      show_item = false;
                    }
                  }
                } else {
                  show_item = false;
                }
              }
              if (show_item) {
                output +=
                  '\n<url>\n  <loc>' + the_base + tail + file + '</loc>\n' +
                  (upd_date ? '\n  <lastmod>' + upd_date.toUTCString() + '</lastmod>' : '') + '\n</url>';
              }
            }
            return output + (['','undefined'].indexOf(tree_output.trim()) == -1 ? tree_output : '');
          }
        };
      return tree(the_head, the_tail, the_base)
          .replace('undefined', '');  // hack, not sure where the extra "undefined" is coming from. TODO: Fix this
    }
-%>
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  <%- generateSitemapXML(public, "/", site.uri.production) %>
</urlset>
