#!/usr/bin/perl -w
# Kiosk hack by Steve <steve@students.zcu.cz>
# auto date controll mechanism added by Fous <honza801@students.zcu.cz>
#
# Copyright © 2001, 2002, 2003, 2004 Jamie Zawinski <jwz@jwz.org>.
#
# Permission to use, copy, modify, distribute, and sell this software and its
# documentation for any purpose is hereby granted without fee, provided that
# the above copyright notice appear in all copies and that both that
# copyright notice and this permission notice appear in supporting
# documentation.  No representations are made about the suitability of this
# software for any purpose.  It is provided "as is" without express or 
# implied warranty.
#
# This program attempts to locate a random image from the specified directory,
# and load it on to the root window, using some other program that can decode
# image files.  (It attempts to find such a program.)
#
# The various xscreensaver hacks that manipulate images ("slidescreen",
# "jigsaw", etc.) get the image to manipulate by running the
# "xscreensaver-getimage" program.
#
# "xscreensaver-getimage" will invoke this program, depending on the
# value of the "chooseRandomImages" and "imageDirectory" settings in
# the ~/.xscreensaver file (or /usr/lib/X11/app-defaults/XScreenSaver).
#
# Created: 12-Apr-01.

require 5;
use diagnostics;
use strict;

use POSIX;
use Fcntl;

use POSIX ':fcntl_h';				# S_ISLNK was here in Perl 5.6
import Fcntl ':mode' unless defined &S_ISLNK;	# but it is here in Perl 5.8

use bytes;  # Larry can take Unicode and shove it up his ass sideways.
            # Perl 5.8.0 causes us to start getting incomprehensible
            # errors about UTF-8 all over the place without this.

##
#### kiosk hack start
use Sys::Hostname;          # pro urceni hostname
# vychozi hodnota priority obrazku, pokud nenispecifikovana v nazvu
my $default_priority = 20;
# vychozi hodnota masky hostname, pokud neni specifikovana v nazvu
my $default_group = "all";
# soubor se skupinami podle rozmisteni kiosku
my $location_file = "/etc/kiosek/location";
#### kiosk hack end
##

my $progname = $0; $progname =~ s@.*/@@g;
my $version = q{ $Revision: 1.3 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;

my $verbose = 0;

# This matches files that we are allowed to use as images (case-insensitive.)
# Anything not matching this is ignored.  This is so you can point your
# imageDirectory at directory trees that have things other than images in
# them, but it assumes that you gave your images sensible file extensions.
#
my $good_file_re = '\.(gif|p?jpe?g|png|tiff?|xbm|xpm)$';

# JPEG, GIF, and PNG files that are are smaller than this size in either
# direction are rejected: this is so that you can use an image directory
# that contains both big images and thumbnails, and have it only select
# the big versions.
#
my $min_image_width  = 255;
my $min_image_height = 255;


# These are programs that can be used to put an image file on the root
# window (including virtual root windows.)  The first one of these programs
# that exists on $PATH will be used (with the file name as the last arg.)
#
# Generally this isn't used any more; when "xscreensaver-getimage" invokes
# this program, it does so with the "-file" argument (meaning that we just
# return the file name) and then xscreensaver-getimage loads that file
# directly.  However, if you invoke "xscreensaver-getimage-file" directly,
# without "-file", this will be used to actually load the image.
#
my @programs = (
  "chbg       -once -xscreensaver -max_grow 4 -max_size 100",
  "xv         -root -quit -viewonly -maxpect +noresetroot -quick24 -rmode 5" .
  "           -rfg black -rbg black",
  "xli        -quiet -fullscreen -onroot -center -border black",
  "xloadimage -quiet -fullscreen -onroot -center -border black",

# this lame program wasn't built with vroot.h:
# "xsri       -scale -keep-aspect -center-horizontal -center-vertical",
);


sub pick_displayer {
  my @names = ();

  foreach my $cmd (@programs) {
    $_ = $cmd;
    my ($name) = m/^([^ ]+)/;
    push @names, "\"$name\"";
    print STDERR "$progname: looking for $name...\n" if ($verbose > 2);
    foreach my $dir (split (/:/, $ENV{PATH})) {
      print STDERR "$progname:   checking $dir/$name\n" if ($verbose > 3);
      return $cmd if (-x "$dir/$name");
    }
  }

  $names[$#names] = "or " . $names[$#names];
  printf STDERR "$progname: none of: " . join (", ", @names) .
                " were found on \$PATH.\n";
  exit 1;
}


my @all_files = ();     # list of "good" files we've collected
my %seen_inodes;        # for breaking recursive symlink loops
my $skip_count = 0;     # number of files skipped, for diagnostic messages
my $dir_count = 1;      # number of directories seen, for diagnostic messages

sub find_all_files {
  my ($dir) = @_;

  print STDERR "$progname: reading dir $dir/...\n" if ($verbose > 2);

  local *DIR;
  if (! opendir (DIR, $dir)) {
    print STDERR "$progname: couldn't open $dir: $!\n" if ($verbose);
    return;
  }
  my @files = readdir (DIR);
  closedir (DIR);

  my @dirs = ();

  foreach my $file (@files) {
    next if ($file =~ m/^\./);      # ignore dot files/dirs

    $file = "$dir/$file";
    my @st = stat($file);
    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
        $atime,$mtime,$ctime,$blksize,$blocks) = @st;

    if ($#st == -1) {
      if ($verbose) {
        my $ll = readlink $file;
        if (defined ($ll)) {
          print STDERR "$progname: dangling symlink: $file -> $ll\n";
        } else {
          print STDERR "$progname: unreadable: $file\n";
        }
      }
      next;
    }

    next if ($seen_inodes{"$dev:$ino"}); # break symlink loops
    $seen_inodes{"$dev:$ino"} = 1;

    if (S_ISDIR($mode)) {
      push @dirs, $file;
      $dir_count++;
      print STDERR "$progname:   found dir  $file\n" if ($verbose > 2);
    } elsif (S_ISREG($mode) || S_ISLNK($mode)) {

      if ($file =~ m/[~%\#]$/ ||               # backup file, or
          ! ($file =~ m/$good_file_re/io)) {   # no image extension
        $skip_count++;
        print STDERR "$progname:   skip file $file\n" if ($verbose > 2);
      } else {
        push @all_files, $file;
        print STDERR "$progname:   found file $file\n" if ($verbose > 2);
      }
    } elsif ($verbose > 2) {
      print STDERR "$progname:   nonreg $file\n";
    }
  }

  foreach (@dirs) {
    find_all_files ($_);
  }
}


##
#### kiosk hack start

#
# nacte ze souboru mapu skupin umisteni. predpoklada se struktura souboru:
# nazev_umistenei:hostname1,hostname2,...
sub read_locations {
  my %locations;
  open LOCATION, "<$location_file" or return;
  while (<LOCATION>) {
    chomp;
    s/\#.*//;
    $_ or next;
    (my $location, my @hosts) = split /[:,]/;
    $locations{$location} = \@hosts;
  }
  close LOCATION;
  return %locations;
}

#
# vytvori seznam souboru, jejichz nazev respektuje localhostname resp. 
# skupinu umisteni stroje (viz. soubor location). v seznamu se kazdy soubor
# vyskytuje tolikrat, kolik udava jeho priorita
sub select_and_prioritize {
  my @files = @_;
  my @prio_img_list;
  my $localhost = hostname();
  my %locations = read_locations();
  # pro kontrolu datumu potrebujeme vedet, jaky je dnes datum
  my @localtime = localtime(time); 
  $localtime[4]=$localtime[4]+1; # upravime mesic+1
  $localtime[5]=$localtime[5]-100; # vraceno jako rodil od 1900, ale my mame uz 2008, chceme jen 2 cisla
  foreach (@localtime) {
  	s/^(\d{1})$/0$1/; # chceme format rrmmdd takze doplnim nuly, kde jsou potreba
  }
  my $now = "$localtime[5]$localtime[4]$localtime[3]";

  foreach my $image (@files) {
    if ($image =~ /.*\/[^:]+(?::([^:]*))?(?::(\d{0,2}))?(?::(\d{6}))?$good_file_re/) {
      my $group = (defined($1) and ("$1" ne "")) ? $1 : $default_group;
      my $priority = (defined($2) and ("$2" ne "")) ? $2 : $default_priority;
      my $date = (defined($3) and ("$3" ne "")) ? $3 : $now;
      if ($date >= $now) { # a kdyz to jeste nebude prosly, tak to soupneme do seznamu imaguu
        my @hosts = (exists $locations{$group}) ? @{$locations{$group}} : $group;
        foreach my $host (@hosts) {
          if ($localhost =~ /$host/) {
            for (my $i = 1; $i <= $priority; $i++) {
	      push @prio_img_list, $image;
	    }
	  }
        }
      }
    }
  }
  return @prio_img_list;
}

#### kiosk hack end
##

sub find_random_file {
  my ($dir) = @_;

  $dir =~ s@/+$@@g;

  print STDERR "$progname: recursively reading $dir...\n" if ($verbose > 1);
  find_all_files ($dir);
  print STDERR "$progname: found " . ($#all_files+1) .
               " file" . ($#all_files == 0 ? "" : "s") .
               " in $dir_count dir" . ($dir_count == 1 ? "" : "s") .
               "; skipped $skip_count file" . ($skip_count == 1 ? "" : "s") .
               ".\n"
    if ($verbose > 1);

#  @all_files = sort(@all_files);         #kiosk hack: vybereme jen urcite soubory
  @all_files = select_and_prioritize(sort(@all_files));

  if ($#all_files < 0) {
    print STDERR "$progname: no files in $dir\n";
    exit 1;
  }

  my $max_tries = 50;
  for (my $i = 0; $i < $max_tries; $i++) {

    my $n = int (rand ($#all_files + 1));
    my $file = $all_files[$n];
    if (large_enough_p ($file)) {
      return $file;
    }
  }

  print STDERR "$progname: no suitable images in $dir " .
               "(after $max_tries tries)\n";
  exit 1;
}


sub display_file {
  my ($file, $displayer) = @_;

  if (!defined($displayer)) {
    print STDOUT "$file\n";
  }  else {
    my @cmd = split (/ +/, $displayer);
    push @cmd, $file;   # do it this way to allow file names with spaces.
    print STDERR "$progname: executing \"" . join(" ", @cmd) . "\"\n"
      if ($verbose);
    exec (@cmd) || die;
  }
}


sub find_and_display {
  my ($dir, $displayer) = @_;
  my $file = find_random_file ($dir);
  display_file ($file, $displayer);
}


sub large_enough_p {
  my ($file) = @_;

  my ($w, $h) = image_file_size ($file);

  if (!defined ($h)) {
    print STDERR "$progname: $file: unable to determine image size\n"
      if ($verbose);
    # Assume that unknown files are of good sizes: this will happen if
    # they matched $good_file_re, but we don't have code to parse them.
    # (This will also happen if the file is junk...)
    return 1;
  }

  if ($w < $min_image_width || $h < $min_image_height) {
    print STDERR "$progname: $file: too small ($w x $h)\n" if ($verbose > 1);
    return 0;
  }

  print STDERR "$progname: $file: $w x $h\n" if ($verbose > 1);
  return 1;
}



# Given the raw body of a GIF document, returns the dimensions of the image.
#
sub gif_size {
  my ($body) = @_;
  my $type = substr($body, 0, 6);
  my $s;
  return () unless ($type =~ /GIF8[7,9]a/);
  $s = substr ($body, 6, 10);
  my ($a,$b,$c,$d) = unpack ("C"x4, $s);
  return (($b<<8|$a), ($d<<8|$c));
}

# Given the raw body of a JPEG document, returns the dimensions of the image.
#
sub jpeg_size {
  my ($body) = @_;
  my $i = 0;
  my $L = length($body);

  my $c1 = substr($body, $i, 1); $i++;
  my $c2 = substr($body, $i, 1); $i++;
  return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);

  my $ch = "0";
  while (ord($ch) != 0xDA && $i < $L) {
    # Find next marker, beginning with 0xFF.
    while (ord($ch) != 0xFF) {
      return () if (length($body) <= $i);
      $ch = substr($body, $i, 1); $i++;
    }
    # markers can be padded with any number of 0xFF.
    while (ord($ch) == 0xFF) {
      return () if (length($body) <= $i);
      $ch = substr($body, $i, 1); $i++;
    }

    # $ch contains the value of the marker.
    my $marker = ord($ch);

    if (($marker >= 0xC0) &&
        ($marker <= 0xCF) &&
        ($marker != 0xC4) &&
        ($marker != 0xCC)) {  # it's a SOFn marker
      $i += 3;
      return () if (length($body) <= $i);
      my $s = substr($body, $i, 4); $i += 4;
      my ($a,$b,$c,$d) = unpack("C"x4, $s);
      return (($c<<8|$d), ($a<<8|$b));

    } else {
      # We must skip variables, since FFs in variable names aren't
      # valid JPEG markers.
      return () if (length($body) <= $i);
      my $s = substr($body, $i, 2); $i += 2;
      my ($c1, $c2) = unpack ("C"x2, $s);
      my $length = ($c1 << 8) | $c2;
      return () if ($length < 2);
      $i += $length-2;
    }
  }
  return ();
}

# Given the raw body of a PNG document, returns the dimensions of the image.
#
sub png_size {
  my ($body) = @_;
  return () unless ($body =~ m/^\211PNG\r/s);
  my ($bits) = ($body =~ m/^.{12}(.{12})/s);
  return () unless defined ($bits);
  return () unless ($bits =~ /^IHDR/);
  my ($ign, $w, $h) = unpack("a4N2", $bits);
  return ($w, $h);
}


# Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
# of the image.
#
sub image_size {
  my ($body) = @_;
  my ($w, $h) = gif_size ($body);
  if ($w && $h) { return ($w, $h); }
  ($w, $h) = jpeg_size ($body);
  if ($w && $h) { return ($w, $h); }
  # #### TODO: need image parsers for TIFF, XPM, XBM.
  return png_size ($body);
}

# Returns the dimensions of the image file.
#
sub image_file_size {
  my ($file) = @_;
  my $body = '';
  local *IN;
  if (! open (IN, "<$file")) {
    print STDERR "$progname: $file: $!\n" if ($verbose);
    return undef;
  }
  binmode (IN);  # Larry can take Unicode and shove it up his ass sideways.
  while (<IN>) {
    $body .= $_;
    last if (length($body) > 1024 * 100);  # the first 100k should be enough
  }
  close IN;
  return image_size ($body);
}


sub usage {
  print STDERR "usage: $progname [--verbose] [--name] file-or-directory\n\n" .
  "       Puts the given image file (or a randomly selected image from the\n" .
  "       given directory) on the root window.  If --name is specified,\n" .
  "       just prints the selected filename to stdout instead.\n\n";
  exit 1;
}

sub main {
  my $dir = undef;
  my $do_name = 0;

  while ($_ = $ARGV[0]) {
    shift @ARGV;
    if ($_ eq "--verbose") { $verbose++; }
    elsif (m/^-v+$/) { $verbose += length($_)-1; }
    elsif ($_ eq "--name") { $do_name++; }
    elsif (m/^-./) { usage; }
    elsif (!defined($dir)) { $dir = $_; }
    else { usage; }
  }

  usage unless (defined($dir));
  my $displayer = undef;

  $displayer = pick_displayer() unless $do_name;

  if (-d $dir) {
    find_and_display ($dir, $displayer);
  } elsif (-f $dir) {
    display_file ($dir, $displayer);
  } else {
    print STDERR "$progname: $dir does not exist\n";
    usage();
  }
}

main;
exit 0;
