#!/usr/bin/perl -w

use strict;
use warnings;

BEGIN {
    unshift @INC, ( $ENV{POPHOME} || '@POPHOME@' ) . '/lib'
      unless $ENV{KUNDE_NO_PERLPATH};
}

use Dbase::Getopt qw(:DEFAULT);
use Dbase::Help qw(DoSelect);
use Loader qw(list_hardware lister show_progress);
use noris::CSV;
use Umlaut qw(textmodus);

use constant SPLIT_RE => qr/\n(?=\S)/;

my $WithNewlines;
GetOptions(
    'csv-option=s' => \my %CSV_Options,
    'einzeilig'    => sub { $WithNewlines = '' },
    'mehrzeilig'   => sub { $WithNewlines = 1 },
);

my ( %attr, @hardware );
DoSelect {
    my ($id) = @_;
    show_progress("$id...\r");
	no warnings 'once';
    lister(5);
    list_hardware($id);
    lister(0);
    push @hardware, {};
    for ( split SPLIT_RE, $Db::output ) {
        s/\n+\z//;
        s/\n +/\n/g;
        s#\n#; #g unless $WithNewlines;
        s/^([^:]+?)\s*: // or die $_;
        next if $_ eq '-';
        $hardware[-1]{$1} = $_;
        ++$attr{$1};
    }
}
<<_;
	SELECT   id
	FROM     hardware
	WHERE    ende IS NULL OR ende >= UNIX_TIMESTAMP(NOW())
	ORDER BY id
_

# Spalten nach Häufigkeit ihrer Verwendung sortieren:
my @attr = sort { $attr{$b} <=> $attr{$a} || $a cmp $b } keys %attr;

textmodus( \*STDOUT );
my $csv = noris::CSV->new( \%CSV_Options );
print $csv->as_decoded_string(@attr);
for my $hardware (@hardware) {
    print $csv->as_decoded_string(
        map exists $hardware->{$_} ? $hardware->{$_} : '', @attr );
}

__END__

=head1 NAME

hardwareliste - gibt die Hardware-Datenbank als CSV-Liste aus

=head1 SYNOPSE

    hardwareliste

=head1 OPTIONEN

=over 4

=item -csv-option Name=Wert

Optionen für L<Text::CSV_XS>, s. Dokumentation dieses Moduls

=item -einzeilig

Zeilenumbrüche in den Texten durch Leerzeichen ersetzen (voreingestellt)

=item -mehrzeilig

Zeilenumbrüche in den Texten erhalten;
führt beim Import in MS-Excel erfahrungsgemäß zu Problemen

=item -help

=item -?

um (nur) diese Dokumentation anzeigen zu lassen

=back

=head1 HINTERGRUND

s. RT#322028

