#!/usr/bin/env perl
# $Id: indent-tty,v 1.4 2016/05/11 23:32:09 tom Exp $
# -----------------------------------------------------------------------------
# Copyright 2016 by Thomas E. Dickey
#
#                         All Rights Reserved
#
# 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 ABOVE LISTED 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.
#
# Except as contained in this notice, the name(s) of the above copyright
# holders shall not be used in advertising or otherwise to promote the
# sale, use or other dealings in this Software without prior written
# authorization.
# -----------------------------------------------------------------------------
# Format the output of stty -a into a single column, allowing diff to show
# just the single feature(s) which may change.

sub indent_tty($) {
    my @data = @{ $_[0] };
    my %data;
    for my $n ( 0 .. $#data ) {
        my $line = $data[$n];
        chomp $line;
        $line =~ s/^\w+://;
        $line =~ s/^\s+//;
        $line =~ s/([\d?]),/$1;/g;
        $line =~ s/([^[:alpha:]][\d?]+)$/$1;/g;
        while ( $line =~ /;/ ) {
            my $part = $line;
            $part =~ s/;.*//;
            $line =~ s/^[^;]*;\s*//;
            my $name = $part;
            $name =~ s/\s.*//;
            $data{$name} = $part;
        }
        while ( $line ne "" ) {
            my $part = $line;
            $part =~ s/\s.*//;
            my $name = $part;
            $name =~ s/^-//;
            $data{$name} = $part;
            last unless ( $line =~ /\s/ );
            $line =~ s/^[^\s]*\s+//;
        }
    }
    for my $key ( sort keys %data ) {
        printf "%s\n", $data{$key};
    }
}

sub do_file($) {
    my $path = shift;
    if ( open FP, $path ) {
        my @data = <FP>;
        close FP;
        &indent_tty( \@data );
    }
}

if ( $#ARGV >= 0 ) {
    while ( $#ARGV >= 0 ) {
        &do_file( shift @ARGV );
    }
}
else {
    if ( open FP, "stty -a |" ) {
        my @data = <FP>;
        close FP;
        &indent_tty( \@data );
    }
}
