/* $Progeny$ */

/* discover-xml.c -- Hardware-querying utility.
 *
 * AUTHOR: Josh Bressers <bressers@progeny.com>
 *
 * Copyright 2002 Progeny Linux Systems, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include "config.h"

#include <assert.h>
#include <err.h>
#include <getopt.h>
#include <stdio.h>
#include <sysexits.h>
#include <ctype.h>
#include <string.h>

#include <discover/discover.h>
#include <discover/discover-conf.h>
#include <discover/discover-xml.h>
#include <discover/device.h>

enum action {
    BUS_SUMMARY,
    TYPE_SUMMARY
};

static char shortopts[] = "d:e:tvVh";
static int verbose = 0;
static int do_model = 1;
static int do_vendor = 1;
static int do_model_id = 0;
static int do_vendor_id = 0;

static struct option longopts[] = {
    /*options */
    { "disable-bus",    required_argument, NULL, 'd' },
    { "enable-bus",     required_argument, NULL, 'e' },
    { "type-summary",   no_argument,       NULL, 't' },
    { "verbose",        no_argument,       NULL, 'v' },
    { "help",           no_argument,       NULL, 'h' },
    { "version",        no_argument,       NULL, 'V' },
    { 0, 0, 0, 0 }
};

static void
print_or_unknown(char *s)
{
    if (s) {
        printf("%s ", s);
    } else {
        fputs("unknown ", stdout);
    }
}

static void
print_usage()
{
    puts("\n\
usage: discover-xml [OPTIONS]\n\
       discover-xml --type-summary [OPTIONS]\n\
       discover-xml --version\n\
       discover-xml --help");
}

static void
print_help()
{
    print_usage();
    puts("\n\
  -t, --type-summary        Summarize by device type.\n\
\n\
OPTIONS\n\
  -d, --disable-bus BUS     Disable the bus BUS.\n\
  -e, --enable-bus BUS      Enable the bus BUS.\n\
  -v, --verbose             Print verbose output.\n\
");
    printf("Report bugs to <%s>.\n", PACKAGE_BUGREPORT);
}

static void
print_version()
{
    puts(PACKAGE_STRING);
}

static void
print_device_list(discover_device_t *device)
{
    for (; device; device = discover_device_get_next(device)) {
        fputs("--", stdout);
        if (do_vendor_id) {
            print_or_unknown(discover_device_get_vendor_id(device));
        }
        if (do_model_id) {
            print_or_unknown(discover_device_get_model_id(device));
        }
        if (do_vendor) {
            print_or_unknown(discover_device_get_vendor_name(device));
        }
        if (do_model) {
            print_or_unknown(discover_device_get_model_name(device));
        }

        putchar('\n');
    }
}

static void
check_status(discover_error_t *status)
{
    if (status != 0) {
        if (status->code == DISCOVER_ESYS) {
            err(EX_OSERR, discover_strerror(status));
        } else {
            errx(status->code, discover_strerror(status));
        }
    }
}

discover_device_t *
type_summary(char *type, discover_bus_map_t *busmap)
{
    discover_device_t *result, *device, *last, *new_device;
    discover_xml_busclass_t *busclasses;
    discover_error_t *status;
    int i;

    assert(type);

    result = last = NULL;

    busmap = discover_conf_get_full_bus_map(status);
    if (status->code != 0) {
        return NULL;
    }

    for (i = 0; busmap[i].name; i++) {
        if (!busmap[i].scan_default) {
            continue;
        }

        busclasses = discover_xml_get_busclasses(i, status);
        if (status->code != 0) {
            return result;
        }
        for (device = discover_xml_get_devices(i, status);
             device;
             device = discover_device_get_next(device)) {
            if (!device->busclass) {
                /* This is a device about which we know nothing. */
                continue;
            }
            if (discover_xml_busclass_cmp(device->busclass, type,
                                          busclasses) == 0) {
                new_device = discover_device_new();
                discover_device_copy(device, new_device);
                new_device->next = NULL;

                if (last) {
                    last->next = new_device;
                    last = new_device;
                } else {
                    result = last = new_device;
                }
            }
        }

        if (status->code != 0) {
            return result;
        }
    }

    if (result) {
        status->code = DISCOVER_SUCCESS;
    } else {
        status->code = DISCOVER_EDEVICENOTFOUND;
    }

    return result;

}

int
main(int argc, char *argv[])
{
    discover_error_t *status;
    discover_bus_map_t *busmap;
    discover_device_t *device;
    enum action action;
    int ch, optindex, i;

    action = BUS_SUMMARY;
    status = discover_error_new();

    while ((ch = getopt_long(argc, argv, shortopts, longopts,
                    &optindex)) != -1) {
        switch (ch) {
        case 'd':
            if (strcmp(optarg, "all") == 0) {
                busmap = discover_conf_get_full_bus_map(status);
                check_status(status);
                for (i = 0; busmap[i].name; i++) {
                    busmap[i].scan_default = 0;
                    if (verbose) {
                        fprintf(stderr, "Disabled %s\n", busmap[i].name);
                    }
                }
            } else {
                busmap = discover_conf_get_bus_map_by_name(optarg,
                        status);
                check_status(status);
                busmap->scan_default = 0;
                if (verbose) {
                    fprintf(stderr, "Disabled %s\n", optarg);
                }
            }
            break;
        case 'e':
            if (strcmp(optarg, "all") == 0) {
                busmap = discover_conf_get_full_bus_map(status);
                check_status(status);
                for (i = 0; busmap[i].name; i++) {
                    busmap[i].scan_default = 1;
                    if (verbose) {
                        fprintf(stderr, "Enabled %s\n", optarg);
                    }
                }
            } else {
                busmap = discover_conf_get_bus_map_by_name(optarg,
                        status);
                check_status(status);
                busmap->scan_default = 1;
                if (verbose) {
                    fprintf(stderr, "Enabled %s\n", optarg);
                }
            }
            break;
        case 't':
            action = TYPE_SUMMARY;
            break;
        case 'h':
            print_help();
            exit(0);
            break;
        case 'V':
            print_version();
            exit(0);
            break;
        case 'v':
            verbose = 1;
            break;
        case 0:
            /* Handled by getopt_long itself (according to the
             * structure we pass).
             */
            break;
        case 1:
            break;
        default:
            print_usage();
            exit(EX_USAGE);
            break;
        }
    }

    argc -= optind;
    argv += optind;

    busmap = discover_conf_get_full_bus_map(status);
    assert(status->code == 0);

    switch(action) {
    case BUS_SUMMARY:
        for (i = 0; busmap[i].name; i++) {
            if (busmap[i].scan_default) {
                printf("%s\n", busmap[i].name);
                device = discover_xml_get_devices(i, status);
                print_device_list(device);
            }
        }
        break;
    case TYPE_SUMMARY:
        if (argc == 0) {
        } else {
            for (i = 0; i < argc; i++) {
                print_device_list(type_summary(argv[i], busmap));
            }
        }
        break;
    default:
        fprintf(stderr, "Internal error: impossible action %d\n", action);
        exit(EX_SOFTWARE);
        break;
    }

    discover_error_free(status);
    return 0;
}

/*
 * Local variables:
 * c-file-style: "progeny"
 * indent-tabs-mode: nil
 * End:
 */
/* vim: set cin fo=tcroq sw=4 et sts=4 tw=75: */
