#!/usr/bin/sh
# Generate rust enums from the term.h header file

list_names() {
    cat /usr/include/term.h | /bin/grep $1 | awk '$1 == "#define" { print $2 "," }'
}

snake_to_camel() {
    sed -e 's/_[a-z]/\U&/g' -e 's/^[a-z]/\U&\E/g' -e 's/_//g'
}

number_key="Number"
bool_key="Booleans"
string_key="Strings"

bools=$(list_names $bool_key | wc -l);
numerics=$(list_names $number_key | wc -l);
strings=$(list_names $string_key | wc -l);

echo "$(cat - <<-EOF
    //! This file was generated by "$0" on $(date).
    //! Please do not modify it.

    /// Number of booleans expected to be present in the file
    pub const PREDEFINED_BOOLEANS_COUNT : usize = $bools;
    
    /// Number of numbers expected to be present in the file
    pub const PREDEFINED_NUMERICS_COUNT : usize = $numerics;
    
    /// Number of strings expected to be present in the file
    pub const PREDEFINED_STRINGS_COUNT  : usize = $strings;

    #[repr(usize)]
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    pub enum BooleanField {
        $(list_names $bool_key | snake_to_camel)
    }

    #[repr(usize)]
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    pub enum NumericField {
        $(list_names $number_key | snake_to_camel)
    }

    #[repr(usize)]
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    pub enum StringField {
        $(list_names $string_key | snake_to_camel)
    }
EOF
)" | rustfmt