#!/usr/bin/env perl
# $Id: indent-tty,v 1.3 2016/05/11 23:32:09 tom Exp $
#
# 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 );
    }
}
