#! /usr/bin/perl

use strict;
use Getopt::Long;

my $redhat_release="/etc/redhat-release";

my $version = undef;
my $id = undef;
my $description = undef;
my $release = undef;
my $codename = undef;
my $all = undef;
my $short = undef;

my $MSG_LSBVER="LSB Version:\t";
my $MSG_DISTID="Distributor ID:\t";
my $MSG_DISTDESC="Description:\t";
my $MSG_DISTREL="Release:\t";
my $MSG_DISTCODE="Codename:\t";
# Description string delimiter
my $DESCSTR_DELI="release";

my $DISTRIB_DESCRIPTION = '';

Getopt::Long::Configure ("bundling");
my $result = GetOptions ("version|v" => \$version,
                         "id|i"      => \$id,
                         "description|d" => \$description,
                         "release|r" => \$release,
                         "codename|c" => \$codename,
                         "all|a" => \$all,
                         "short|s" => \$short);

if ( ! -e $redhat_release )
{
    exit 1;
}

open(RF, "< $redhat_release") or die "Cannot open $redhat_release: $!";
while (<RF>)
{
    $DISTRIB_DESCRIPTION = $_;
    chomp($DISTRIB_DESCRIPTION);
    last;
}

if($version || $all)
{
    print "$MSG_LSBVER" if ( ! $short );
    print "n/a\n";
}

if($id || $all)
{
    my $tmp = $DISTRIB_DESCRIPTION;
    $tmp =~ s/\slinux\s/ /ig;
    $tmp =~ s/(.+)\s$DESCSTR_DELI.*/$1/;
    $tmp =~ s/\s//g;
    print "$MSG_DISTID" if ( ! $short );
    print "$tmp\n";
}

if($description || $all)
{
    print "$MSG_DISTDESC" if ( ! $short );
    print "$DISTRIB_DESCRIPTION\n";
}

if($release || $all)
{
    my $tmp = $DISTRIB_DESCRIPTION;
    $tmp =~ s/.*$DESCSTR_DELI\s*(\d[[:graph:]]*).*/$1/;
    print "$MSG_DISTREL" if ( ! $short );
    print "$tmp\n";
}

if($codename || $all)
{
    my $tmp = $DISTRIB_DESCRIPTION;
    $tmp =~ s/.*$DESCSTR_DELI.*\((.*)\).*/$1/;
    print "$MSG_DISTCODE" if ( ! $short );
    print "$tmp\n";
}
