#!/usr/bin/perl -w
# $Id: show-dircolors,v 1.1 2016/11/13 15:45: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.
# -----------------------------------------------------------------------------
# Read the database printed by "dircolors -p" and show the different patterns
# with the indicated color by (as done by GNU ls) using hardcoded SGR
# sequences.
#
# The output can be viewed with "less -R".
#
# See
# http://askubuntu.com/questions/17299/what-do-the-different-colors-mean-in-the-terminal
# which uses the LS_COLORS variable.

use strict;

our $comment = "\e[31m";
our $reset   = "\e[K\e[m";

our @data;

open my $fh, "dircolors -p|" or die "cannot read from dircolors";
@data = <$fh>;
close $fh;

printf "\e[H\e[2J";

for my $n ( 0 .. $#data ) {
    chomp $data[$n];
    if ( $data[$n] =~ /^\s*#/ ) {
        printf "%s%s%s\n", $comment, $data[$n], $reset;
    }
    elsif ( $data[$n] =~ /^\s*TERM\s/ ) {
        printf "%s\n", $data[$n];
    }
    elsif ( $data[$n] =~ /^\s*[^\s]+\s+\d+(;\d+)?\s*(#.*)?$/ ) {
        my $code = $data[$n];
        $code =~ s/^\s*[^\s]+\s+//;
        $code =~ s/\s.*//;
        my $data = $data[$n];
        $data =~ s/(#.*)$/$comment$1$reset/;
        $data =~ s/^(\s*)([^\s]+)(\s+)/$1\e[${code}m$2\e[m$3/;
        printf "%s\n", $data;
    }
    else {
        printf "%s\n", $data[$n];
    }
}

1;
