/*
 * dnsutl - utilities to make DNS easier to configure
 * Copyright (C) 1995, 1996, 1999, 2006, 2007 Peter Miller
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <ac/stdio.h>
#include <ac/string.h>

#include <arglex.h>
#include <error.h>
#include <ethers.h>
#include <mem.h>
#include <srrf/reader.h>

int             verbose;


static string_ty *
first_part(string_ty *s)
{
    char            *dot;

    dot = strchr(s->str_text, '.');
    if (!dot)
        return str_from_c("");
    return str_n_from_c(s->str_text, dot - s->str_text);
}


void
ethers(const char *infile, const char *outfile)
{
    FILE            *fp;
    srrf_t          *rp;
    srrf_list_ty    *rlp;
    size_t          j;
    srrf_class_ty   *the_class;
    srrf_type_ty    *the_type;

    /*
     * read the input file
     */
    rlp = srrf_reader(infile, verbose, 1);

    /*
     * open the output file
     */
    if (outfile)
    {
        fp = fopen(outfile, "w");
        if (!fp)
            nfatal("creat \"%s\"", outfile);
    }
    else
    {
        outfile = "(stdout)";
        fp = stdout;
    }

    /*
     * find the necessary type pointer
     */
    the_class = srrf_class_by_name("ether");
    assert(the_class);
    the_type = srrf_type_by_name(the_class, "a");
    assert(the_type);

    /*
     * warning comment at the top of the file
     */
    fprintf(fp, "# Do not edit this file.  It is generated\n");
    fprintf
    (
        fp,
        "# using a '%s %s %s' command.\n",
        progname,
        (infile ? infile : "-"),
        (fp == stdout ? "-" : outfile)
    );

    /*
     * scan the resources looking for hosts
     */
    for (j = 0; j < rlp->nrecords; ++j)
    {
        string_ty       *tmp;

        rp = rlp->record[j];
        if (rp->type != the_type)
            continue;

        /*
         * Print the ethernet address and the name.
         */
        tmp = first_part(rp->name);
        fprintf(fp, "%s %s\n", rp->arg.string[0]->str_text, tmp->str_text);
        str_free(tmp);
    }

    /*
     * close the output file
     */
    if (fflush(fp))
        nfatal("write \"%s\"", outfile);
    if (fp != stdout && fclose(fp))
        nfatal("close \"%s\"", outfile);
}


syntax highlighted by Code2HTML, v. 0.9.1