#!/usr/bin/perl -w
#
# Author:  Ulrich Leodolter <ulrich.leodolter@obvsg.at>
# Date:    2008-09-24
# Comment: display lstat and encode like bacula,
#          to_base64() converted from bacula source.
# 
use strict;
use Digest::SHA1;

my $filename = shift;
die "missing filename parameter\n" unless (defined $filename);

my @base64_digits =
(
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
  'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
);

#/* Convert a value to base64 characters.
# * The result is stored in where, which
# * must be at least 8 characters long.
# *
# * Returns the number of characters
# * stored (not including the EOS).
# */
sub to_base64
{
    my $value = shift;
    my @where;

    my $val;
    my $i = 0;
    my $n;

    #/* Handle negative values */
    if ($value < 0) {
	$where[$i++] = '-';
	$value = -$value;
    }

    #/* Determine output size */
    $val = $value;
    do {
	$val >>= 6;
	$i++;
    } while ($val);
    $n = $i;

    #/* Output characters */
    $val = $value;
#   $where[$i] = 0;
    do {
	$where[--$i] = $base64_digits[$val & 0x3F];
	$val >>= 6;
    } while ($val);
    return join('',@where);
}



my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
    $atime,$mtime,$ctime,$blksize,$blocks)
    = lstat($filename);

printf "dev      = %10s %s\n", $dev, to_base64($dev);
printf "ino      = %10s %s\n", $ino, to_base64($ino);
printf "mode     = %10s %s\n", $mode, to_base64($mode);
printf "nlink    = %10s %s\n", $nlink, to_base64($nlink);
printf "uid      = %10s %s\n", $uid, to_base64($uid);
printf "gid      = %10s %s\n", $gid, to_base64($gid);
printf "rdev     = %10s %s\n", $rdev, to_base64($rdev);
printf "size     = %10s %s\n", $size, to_base64($size);
printf "atime    = %10s %s\n", $atime, to_base64($atime);
printf "mtime    = %10s %s\n", $mtime, to_base64($mtime);
printf "ctime    = %10s %s\n", $ctime, to_base64($ctime);
printf "blksize  = %10s %s\n", $blksize, to_base64($blksize);
printf "blocks   = %10s %s\n", $blocks,to_base64($blocks);

# calc md5 sum
my $md5 = Digest::SHA1->new;

open(CHECK, "<", $filename) or die $!;
binmode(CHECK);
$md5->addfile(*CHECK);
close(CHECK);

my $digest = $md5->b64digest;
printf "sha1     = %s\n", $digest;

### end

