#!/usr/bin/perl
# fconfig - manipulate RedBoot flash configuration data
# Copyright 2009 Canonical Ltd.
#
# 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
# SOFTWARE IN THE PUBLIC INTEREST, INC. 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.
#
# Except as contained in this notice, the name of the author shall not be used
# in advertising or otherwise to promote the sale, use or other dealings in
# this Software without prior written authorization from the author.
#
# perl-depends: Getopt::Long
#
# TODO
# - pod2usage integration?  see also Getopt::Long's auto_help
# - $main::VERSION / --version support
# - check whether type=empty keys make sense
# - endianness and type sizes:
#   * RedBoot uses native endianness (e.g. KEY1 and KEY2 are declared as
#     unsigned long in the struct and mapped) by default
#   * the flash byte order is used for CRC
#   * long is assumed to be 4 bytes long:
#        struct _config {
#            unsigned long len;
#            unsigned long key1;
#            char config_data[MAX_CONFIG_DATA-(4*4)];
#            unsigned long key2;
#            unsigned long cksum;
#        };
#     (4*4 is 4 bytes for the 4 values len, key1, key2, and cksum)
#   * endianness is automatically flipped if REDBOOT_FLASH_REVERSE_BYTEORDER is
#     set, which is when flash endianness
#     (CYGOPT_REDBOOT_FLASH_BYTEORDER_MSBFIRST or
#     CYGOPT_REDBOOT_FLASH_BYTEORDER_LSBFIRST) and platform endianness
#     (CYG_BYTEORDER; can be CYG_LSBFIRST or CYG_MSBFIRST) differ; according to
#     packages/hal/arm/arch/current/include/basetype.h, the assumed platform
#     endianness is set to LE on ARMEL (CYG_LSBFIRST) and to BE on ARMEB
#     (CYG_MSBFIRST), so to platform endianness; the flash endianness seems to
#     be optional, so it seems the default is to use native endianness
#     everywhere
#   * => fconfig should work in one internal endianness
#   * => fconfig should allow detecting the flash's endianness based on the
#        magic keys
#   * => fconfig should require an endianness setting when initializing but
#        could perhaps default to host endiannness
#   * => fconfig should allow setting an endianness when reading but could
#        perhaps default to sniffing
# - need to check size in set mode as it might overflow
# - handle partial reads
# - make sure -n, -d, -f aren't used as there are used in RedBoot:
#    init_opts(&opts[0], 'l', false, OPTION_ARG_TYPE_FLG,.
#              (void *)&list_only, (bool *)0, "list configuration only");
#    init_opts(&opts[1], 'n', false, OPTION_ARG_TYPE_FLG,.
#              (void *)&nicknames, (bool *)0, "show nicknames");
#    init_opts(&opts[2], 'f', false, OPTION_ARG_TYPE_FLG,.
#              (void *)&fullnames, (bool *)0, "show full names");
#    init_opts(&opts[3], 'i', false, OPTION_ARG_TYPE_FLG,.
#              (void *)&init, (bool *)0, "initialize configuration database");
#    init_opts(&opts[4], 'd', false, OPTION_ARG_TYPE_FLG,.
#              (void *)&dumbterminal, (bool *)0, "dumb terminal: no clever edits"
# - allow setting size in all modes
# - use an external CRC32 function and/or init the table dynamically; these
#   packages are confirmed not to provide the mean to compute our CRC32:
#   libstring-crc32-perl
# - provide default values for upstream default entries
#
# Author: Loïc Minier <lool@dooz.org>

use strict;
use warnings;

# inet_aton() and inet_ntoa(); Socket.pm is in the perl-base Debian package
# which is Essential: yes
use Socket;

###### Start of CRC part
# This part is adapted from ecos/packages/services/crc/current/src/crc32.c
# /*  COPYRIGHT (C) 1986 Gary S. Brown.  You may use this program, or       */
# /*  code or tables extracted from it, as desired without restriction.     */
# /*                                                                        */
# /*  First, the polynomial itself and its table of feedback terms.  The    */
# /*  polynomial is                                                         */
# /*  X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0   */
# /*                                                                        */
use constant crc_table => [
      0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
      0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
      0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
      0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
      0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
      0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
      0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
      0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
      0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
      0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
      0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
      0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
      0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
      0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
      0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
      0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
      0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
      0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
      0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
      0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
      0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
      0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
      0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
      0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
      0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
      0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
      0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
      0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
      0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
      0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
      0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
      0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
      0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
      0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
      0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
      0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
      0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
      0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
      0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
      0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
      0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
      0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
      0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
      0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
      0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
      0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
      0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
      0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
      0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
      0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
      0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
      0x2d02ef8d
];

sub crc32 {
    my $data = shift;
    my $val = 0;

    for my $byte (unpack("C*", $data)) {
        $val = crc_table->[($val ^ $byte) & 0xff] ^ ($val >> 8);
    }
    return $val;
}
###### End of CRC part

# see redboot/current/include/flash_config.h in ecos/packages
# XXX allow for config/platform overrides
use constant config_types => {
    empty => {
        type => 0,
        default_value_size => undef, # should never use default size
        parse => undef,
    },
    bool => {
        type => 1,
        default_value_size => 4, # XXX == sizeof(bool) can be 2 or 4; often sizeof(int) which itself is often 4
        parse => \&parse_bool,
    },
    int => {
        type => 2,
        default_value_size => 4, # XXX == sizeof(unsigned long) can be 2 or 4; expected to be 4 with GNU
        parse => \&parse_uint32,
    },
    string => {
        type => 3,
        default_value_size => 128, # XXX MAX_STRING_LENGTH from platform config
        parse => \&parse_asciiz,
    },
    script => {
        type => 4,
        default_value_size => 512, # XXX MAX_SCRIPT_LENGTH from platform config
        parse => \&parse_asciiz,
    },
    ip => {
        type => 5,
        default_value_size => 4, # XXX == sizeof(in_addr_t); under Linux "typedef uint32_t in_addr_t;" so probably 4
        parse => \&parse_in_addr,
    },
    esa => {
        type => 6,
        default_value_size => 8, # XXX should be sizeof(enet_addr_t) but is actually 8 for alignment; "typedef unsigned char enet_addr_t[6];" in redboot/current/include/net/net.h
        parse => \&parse_enet,
    },
    netport =>  {
        type => 7,
        default_value_size => 128, # XXX MAX_STRING_LENGTH from platform config
        parse => \&parse_asciiz,
    },
};

# see redboot/current/src/fconfig.c
use constant standard_default_config_entries => {
    boot_script => {
        description => "Run script at boot",
        type => config_types->{bool}{type},
        sensed_key => "",
        sensing => "true",
        value => "false",
    },
    boot_script_data => {
        description => "Boot script",
        type => config_types->{script}{type},
        sensed_key => "boot_script",
        sensing => "true",
        value => "",
    },
    boot_script_timeout => {
        description => "Boot script timeout (1000 ms resolution)", # XXX CYGNUM_REDBOOT_BOOT_SCRIPT_TIMEOUT_RESOLUTION
        type => config_types->{int}{type},
        sensed_key => "boot_script",
        sensing => "true",
        value => 0,
    },
    console_baud_rate => {
        description => "Console baud rate",
        type => config_types->{int}{type},
        sensed_key => "",
        sensing => "true",
        value => 115200, # XXX CYGNUM_HAL_VIRTUAL_VECTOR_CONSOLE_CHANNEL_BAUD
    },
};

# either '' to use native endianness, '>' for big-endian, or '<' for
# little-endian; as used in pack/unpack; defaults to undef and is set by
# sniffing
my $flash_endianness;

# magic in native endianness
my $config_key1 = 0x0BADFACE;
my $config_key2 = 0xDEADDEAD;

# XXX handle verbosity
sub log_i {
    print STDERR "I: " . join(' ', @_) . "\n";
}

sub usage {
    my ($fh, $exit) = @_;
    $fh = \*STDERR unless $fh;
    $exit = 1 unless $exit;

    print $fh <<EOF
Usage:
    fconfig -f <file> [<options>] [<mode>] [<mode options>]

Common options:
    -f|--file <file>    file backing the RedBoot config data
    [-o|--offset <offset>]
                        offset of RedBoot config data in file; defaults to 0
    [-v|--verbose]      increase verbosity
    [-h|--help]         print help

Mode selection and mode options:
    The default mode is an interactive mode with prompting for each value.

    -l|--list [-a|--all]
                        list keys and values; --all includes disabled keys
    -i|--init [--size <size>]
                        initialize an empty RedBoot config; size sets the size
                        of the config data; defaults to file size
    -g|--get [--type] [--value] [--sensing] [--sensed-key] [--data-only]
             <key> [<key> ...]
                        get data on named key(s); --data-only only prints the
                        requested data
    -s|--set [--type <type>] [--value <value>] [--sensing <sensing>]
             [--sensed-key <sensed key>] <key>
                        set named key's data or add named key with data
EOF
;
    exit $exit;
}

use Getopt::Long;

my $file;
my $offset = 0;
my $verbose;
my $mode;
my $all;
my $size;
my $title;
my $type;
my $value;
my $sensing;
my $sensed_key;

sub set_mode($) {
    die "Mode already set to $mode.\n\n" if $mode && $_[0] ne $mode;
    $mode = shift;
}

if (not GetOptions(
            # common options
            "f|file=s"          => \$file,
            "o|offset:o"        => \$offset,
            "v|verbose"         => \$verbose,
            "h|help"            => sub { usage \*STDOUT, 0; },
            # mode selection
            "l|list"            => sub { set_mode('list') },
            "i|init"            => sub { set_mode('init') },
            "g|get"             => sub { set_mode('get') },
            "s|set"             => sub { set_mode('set') },
            # mode options
            "a|all"             => \$all,
            "size:o"            => \$size,
            "title"             => \$title,
            "type:s"            => \$type,
            "value:s"           => \$value,
            "sensing:s"         => \$sensing,
            "sensed-key:s"      => \$sensed_key,
            )) {
    usage;
}

# default mode
$mode = 'prompt' unless $mode;

sub die_help {
    print STDERR join(' ', @_) . "\n\n";
    usage
}

# common options
die_help "Need a RedBoot config data file."
    if not defined($file);

# NB: $offset is validated after opening $file

# mode-specific options
die_help "Can only list all keys in list mode."
    if $all and $mode ne 'list';
die_help "Can only set size in init mode."
    if $size and $mode ne 'init';
die_help "Can only request title in get mode."
    if defined($title) and $mode ne 'get';

# XXX need to exclude more flags for prompt, list, and init modes

sub check_get_flag($$) {
    my ($var, $name) = @_;

    die_help "Can't set $name in get mode."
        if defined($$var) and $$var ne '';
}

if ($mode eq 'get') {
    check_get_flag(\$type,       "type");
    check_get_flag(\$value,      "value");
    check_get_flag(\$sensing,    "sensing");
    check_get_flag(\$sensed_key, "sensed-key");
}

if ($mode eq 'set') {
    die_help "Set type to one of bool, int, string, script, ip, esa, netport."
        if defined($type) and not grep($type, ('bool', 'int', 'string', 'script', 'ip', 'esa', 'netport'));
    # XXX parse value
    die_help "Set sensing to if-enabled or if-disabled."
        if defined($sensing)
           and not grep(/^\Q$sensing\E$/, ('if-enabled', 'if-disabled'));
    # XXX check sensed-key exists?
}

sub prompt_on_key($) {
    my $key = shift;

    print ""
}

sub list_on_key($$) {
    my $all_entries = shift;
    my $entry = shift;

    # XXX should use key description instead of name
    print $entry->{key} . ": " . $entry->{value} . "\n";
}

my $on_key_sub;

for ($mode) {
    /prompt/ && do { $on_key_sub = \&prompt_on_key; last; };
    /list/   && do { $on_key_sub = \&list_on_key;   last; };
    #/init/   $on_key_sub = \&init_on_key; $open_mode = "+<";;
    #/get/    $on_key_sub = \&get_on_key;
    #/set/    $on_key_sub = \&set_on_key; $open_mode = "+<";
    //       && die "Internal error: unhandled mode $mode\n";
}

sub load_flash_data($$$) {
    my ($file, $offset, $size) = @_;

    open  F, '<', $file or die  "open $file: $!\n";
    seek  F, $offset, 0 or die  "seek $file: $!\n";

    my $read_chars = 0;
    my $data = '';
    while ($read_chars < $size) {
        my $ret = read F, $data, $size - $read_chars, $read_chars;
        die "read $file: $!\n" unless $ret;
        $read_chars += $ret;
    }

    close F             or die "close $file: $!\n";

    return $data;
}

# $flash_endianness is sniffed if undefined
# $length is sniffed if undefined
sub read_flash_config() {
    # read two longs from flash at beginning of config (length and key1)
    my $flash_start_data = load_flash_data($file, $offset, 8);

    my ($length, $key1);
    if (defined($flash_endianness)) {
        ($length, $key1) = unpack "L" . $flash_endianness . "2", $flash_start_data;
    } else {
        # if flash_endianness is unset, sniff endianness
        foreach my $e ('>', '<') {
            ($length, $key1) = unpack "L" . $e . "2", $flash_start_data;
            if ($key1 == $config_key1) {
                log_i("Sniffed flash endianness as " . ($e eq '<' ? "little" : "big") . " endian.");
                $flash_endianness = $e;
                last;
            }
        }
        die "Could not sniff endianness\n" unless $flash_endianness;
    }

    # verify or sniff size
    die "Config data length doesn't match size\n"
        if defined($size) and $size != $length;
    $size = $length;
    log_i sprintf("Sniffed size of 0x%08X (%u) bytes.", $size, $size);

    # read config data
    my $flash_data = load_flash_data($file, $offset, $size);

    # two longs at end of config data (key2 and checksum)
    my $flash_end_data = substr $flash_data, $size - 8, 8;

    # verify key2
    my ($key2, $checksum) = unpack "L$flash_endianness" . "2", $flash_end_data;
    die "Invalid second magic key\n" if $key2 != $config_key2;

    # verify checksum
    # flip endianness of config data
    my $native_data = pack "L*", unpack("L$flash_endianness*", $flash_data);
    my $crc = crc32(substr($native_data, 0, $size - 4));
    die "Checksum mismatch\n" if $crc != $checksum;

    return $flash_data;
}

my $native_data = read_flash_config();

sub type_info($) {
    my $type = shift;

    my @matching_types = grep { config_types->{$_}{type} == $type } keys(%{+config_types});
    if (@matching_types == 0) {
        die "Internal error: no type with number $type\n";
    }
    if (@matching_types > 1) {
        die "Internal error: type number $type isn't unique\n";
    }
    return config_types->{$matching_types[0]};
}

# returns the length of the data value for the specified type
sub config_data_value_length($) {
    my $type_info = shift;

    # XXX be clever on guessing values
    # XXX log a warning that we're using a default length

    return $type_info->{default_value_size};
}

# XXX need to check what happens with 8-bits data
sub parse_asciiz($) {
    my $native_data = shift;

    # XXX should verify length of native data

    return unpack("A*", $native_data);
}

sub parse_bool($) {
    my $native_data = shift;

    if (length($native_data) != 4) {
        die "Invalid data size for bool\n";
    }

    return parse_uint32($native_data) ? "true" : "false";
}

sub parse_uint32($) {
    my $native_data = shift;

    if (length($native_data) != 4) {
        die "Invalid data size for uint32\n";
    }

    return unpack("L$flash_endianness", $native_data);
}

# XXX RedBoot avoids printing 0.0.0.0 for IP addresses
# XXX need to check data order is correct
sub parse_in_addr($) {
    my $native_data = shift;

    if (length($native_data) != 4) {
        die "Invalid data size for in_addr\n";
    }

    return inet_ntoa($native_data);
}

# XXX need to check data order is correct
sub parse_enet($) {
    my $native_data = shift;

    if (length($native_data) != 8) {
        die "Invalid data size for enet\n";
    }

    return sprintf("%02X:" x 5 . "%02X", unpack("C6", $native_data));
}

sub parse_config_entries($) {
    my $native_data = shift;

    # skip the first two longs (length and key1)
    my $start_offset = 8;
    # length of all config entries, i.e. length minus four longs (keys,
    # checksum, and config length)
    my $config_data_length = length($native_data) - 8 - 8;

    if ($config_data_length < 0) {
        die "Internal error: config data too small\n";
    }

    my $offset = $start_offset;

    my @config_entries = ();
    while (1) {
        my %entry = ();

        # need at least one byte for the data type
        if ($config_data_length - ($offset - $start_offset) < 1) {
            die "Type offset " . $offset . " is outside of config data\n";
        }
        # read data type; this is assumed to be unsigned as RedBoot currently
        # uses values 0 to 7, but internally it uses "char" and "int" types to
        # store it
        my $type = unpack "C", substr($native_data, $offset, 1);
        $offset++;
        if ($type == config_types->{empty}{type}) {
            last;
        }
        my $type_info = type_info($type);
        $entry{type_info} = $type_info;

        # need at least 3 more bytes to read length of key name, sensing,
        # length of sensed key name
        if ($config_data_length - ($offset - $start_offset) < 3) {
            die "Config data offset " . $offset . " is outside of config data\n";
        }
        my ($key_length, $sensing, $sensed_key_length) = unpack "C3", substr($native_data, $offset, 3);
        $offset += 3;

        my $value_length = config_data_value_length($type_info);
        if ($config_data_length - ($offset - $start_offset) < $key_length + $sensed_key_length + $value_length) {
            die "Config data value offset " . $offset . " is outside of condig data\n";
        }
        # XXX might not be 8-bits clean
        my ($key, $sensed_key) = unpack 'A' . $key_length . 'A' . $sensed_key_length, substr($native_data, $offset, $key_length + $sensed_key_length);
        $offset += $key_length + $sensed_key_length;

        my $value_native_data = substr($native_data, $offset, $value_length);
        $offset += $value_length;

        $entry{type}            = $type;
        $entry{key}             = $key;
        $entry{sensed_key}      = $sensed_key;
        $entry{sensing}         = $sensing;
        $entry{native_data}     = $value_native_data;
        $entry{value}           = $type_info->{parse}->($value_native_data);
        push @config_entries, \%entry;
        # XXX debug
        #print "Found key :$key: of type :$type: sensing :$sensed_key: with data length $value_length; value:" . $entry{value} . ":\n";
    }
    return @config_entries;
}

my @config_entries = parse_config_entries($native_data);

# XXX should verify consistency here (e.g. sensed keys)

sub get_entry($$) {
    my $all_entries = shift;
    my $key = shift;

    my @entries = grep { $key eq $_->{key} } @{$all_entries};
    if (@entries == 0) {
        return undef;
    } elsif (@entries != 1) {
        die "Multiple entries with name $key\n";
    }
    return $entries[0];
}

# XXX this might not work in all cases in prompt mode as it assumes the
# sensed_keys are listed first
foreach my $entry (@config_entries) {
    my ($key, $sensed_key, $sensing) = ($entry->{key}, $entry->{sensed_key}, $entry->{sensing});
    if ($all or not $sensed_key) {
        $on_key_sub->(\@config_entries, $entry);
    } else {
        my $sensed_entry = get_entry(\@config_entries, $sensed_key);

        if ($sensed_entry->{type} != config_types->{bool}{type}) {
            die "Expected type bool for sensed key $sensed_key\n";
        }

        if (( $sensing and ($sensed_entry->{value} eq 'true')) or
            (!$sensing and ($sensed_entry->{value} eq 'false'))) {
            $on_key_sub->(\@config_entries, $entry);
        }
    }
}
#map { $on_key_sub->(\@config_entries, $_) } @config_entries;

