#!/usr/bin/perl
# heuristics for identifying os, version and architecture to be written into /etc/opt/a2e/osverarch for use in /etc/adv/mktdir/include/Makefile, hostsyskonfig.tmpl etc
# improved file:/phm/23/01/24/sig/_lng.phm_pub_sig230124.txt::osverarch

my $ver = '';
my $os = '';
my %KV = ();

OS_RELEASE: {
    my $fi = '/etc/os-release';
  TRY: {
      last if -r $fi;
      $fi = '/usr/lib/os_release';
      last if -f $fi;
      last OS_RELEASE;
    };
    my $hi = new IO::File $fi, 'r' or die "failed to read from $fi";
    while (<$hi>) {
	# print $_;
	chomp;
	m(\A(\w+)\=\"(.*)\"\Z);
	next unless $1;
	$KV{$1} = $2;
    };
    $hi->close;
    $ver = $KV{VERSION};
    $os = 'suse' if $KV{NAME} =~ m(\AopenSUSE);
    # print "got os $os ver $ver\n";
};

sub sysout { local $_ = join ' ', @_;$_ = `$_`;chomp;$_ };
my $arch =  &sysout('arch') || &sysout('uname', '-i');

TRY_ISSUE: {
     last if $os and $ver;
     my $fi = '/etc/issue';
     last unless -r $fi;
     my $fh = new IO::File $fi, 'r';
     while (<$fh>) {
	 ($os,$ver) = m(\b(openSUSE)\s*(\S+)\b);
	 last if $ver;
     }
     $fh->close;
     # do { warn  sprintf 'system and version version not found in %s', $fi;last } unless $os and $ver;
};

LSB_RELEASE: {
    last if $os and $ver;
    my @lns = split "\n", &sysout('lsb_release', '-a');
    # file:/phm/23/01/24/sig/_log08adv.phm_pub_sig230124.txt::41982
    for (@lns) {
	chomp;
	m(\A(.*):\s+(.*)\Z);
	$1 =~ s(\s)(_)g;
	$KV{$1} = $2;
    };
    $os = 'suse' if 'OpenSUSE' eq $KV{Distributor_ID};
    $ver = $KV{RELEASE};
};

PROFILE: {
     last if $arch;
     $fi = '/etc/profile.d/site.csh';
     $fh = new IO::File $fi;
     my $arch = '';
     while (<$fh>) {
	 ($arch) = m(\/usr\/share\/site\/(\w+)\-);
	 last if $arch;
     };
     $fh->close;
     do { warn sprintf 'architecture not found in %s', $fi;last } unless $arch;
     $arch =~ s(\bx)(xf);
};

VERS: {
    my @vers = split m(\.), $ver;
    last unless @vers;
    $ver = join '', map { sprintf '%02d', $_ } @vers;
    # print "got ver $ver\n";
};

$os ||= 'suse';

print join '_', $os.$ver, $arch;
