#!/usr/bin/perl5
## Copyright (c) 2001 by FUNIX BV All rights reserved.
##   PROJECT
##     picbrows
##   NAME
##     $Id: download.pl,v 1.3 2007/02/01 08:30:30 maarten Exp $
##   DESCRIPTION
##     Download zip file of a gallery
##     Script tests if the zip directory isn't too full.
##     Script creates a zip file with the gallery id as name in the zip
##     directory. If the file already exists it does nothing.
##     Script serves the zip file with a logical name to the client.
##   DEPENDECIES
##     zip must be present on the host
package download_pl;

use strict;
use vars qw(%g);

use CGI;
$CGI::POST_MAX=1;     # no posts
$CGI::DISABLE_UPLOADS = 1;  # no file uploads
use CGI::Carp qw(fatalsToBrowser);

require Gen::DBIWrap;
require IniConf;

if (!$ENV{'FASTCGIHANDLER'}){
   unshift(@INC,'../lib');
}

require PBGeneric;

if (!$ENV{'FASTCGIHANDLER'}){
   my $lCgi=new CGI;
   my $lCfg=new IniConf('../conf/picbrows.ini');
   main([$lCgi,$lCfg]);
}

return 1;

sub main
{
   my ($aParams)=@_;
   
   %g=(
      'cgi'=>$aParams->[0],
      'cfg'=>$aParams->[1],
      'dbh'=>undef,
      'now'=>new CDateTime
   );
   my %actions=(
      'default'=>\&createZipFile
   );
   my $action=$g{cgi}->param('a');
   if (!$action || !exists $actions{$action}){
      $action='default';
   }
   $g{'dbh'}=Gen::DBIWrap::openConnection($g{'cfg'}->get('db_connection'));
   &{$actions{$action}}();
   $g{'dbh'}->disconnect();
}

sub setLowPriority
{
   my $PRIO_PROCESS=0;
   setpriority($PRIO_PROCESS,$$,20);
}

sub testZipDir
{
   my $lZipDir=$g{'cfg'}->get('loc_zip_dir');
   my $lMaxUsage=int($g{'cfg'}->get('zip_max_du'))*1024;
   # output of du is "<usage> <directory>"
   my $lCmd=$g{'cfg'}->get('du_path');
   my $lUsage=`$lCmd -k "$lZipDir"`;
   $lUsage=~s/^ *(\d*).*$/$1/;
   $lUsage=int($lUsage);
   if ($lUsage<$lMaxUsage){
      return 1;
   }
   return 0;
}

sub createZipFile
{
   my $lTemplate=PBGeneric::loadTempl($g{cfg},"downloadpage.html",1);
   my $lGalleryId=$g{'cgi'}->param('g');
   my $lGallery=new Gallery($lGalleryId);
   if ($lGallery->read($g{'dbh'})){
      # gallery must be activated & must contain pictures
      if ($lGallery->active eq 'Y' && $lGallery->getNrOfPictures($g{'dbh'})>0){
         if (testZipDir()){
            # low priority
            setLowPriority();
            # create zip file
            my $lZipFileName=getGalleryZipFileName($lGalleryId);
            my $lZipFilePath=$g{'cfg'}->get('loc_zip_dir').'/'.$lZipFileName;
            if (!-f $lZipFilePath){
               # file doesn't exist yet
               my $lGalleryDir=$g{'cfg'}->get('loc_picture_dir').$lGallery->dirPath.'/';
               system($g{'cfg'}->get('zip_path').' -j '.$lZipFilePath.' '.$lGalleryDir.'*.jp*g');
            }
            #showDownloadPage($lTemplate);
            print CGI::redirect($g{'cfg'}->get('host_zip_dir').'/'.$lZipFileName);
         } else {
            # show error message
            showDownloadPage($lTemplate,'Temporary file space is full, please try it again tomorrow');
         }
      } else {
         showDownloadPage($lTemplate,'Invalid gallery!');
      }
   } else {
      showDownloadPage($lTemplate,'Invalid gallery!');
   }
}

sub getGalleryZipFileName
{
   my ($aGalleryId)=@_;

   my $galleryList=new GalleryList;
   my $galleries=$galleryList->readParents($g{'dbh'},$aGalleryId);
   my $lFileName='';
   for (@{$galleries}){
      $lFileName.=$_->name.'_';
   }
   # replace " " with "_" and remove last _
   $lFileName=~s/ /_/g;
   $lFileName=substr($lFileName,0,length($lFileName)-1);
   $lFileName.='.zip';

   return $lFileName;
}

sub showDownloadPage
{
   my ($aTemplate,$aErrorText)=@_;

   if (length($aErrorText)>0){
      $aTemplate->SetVar('Prepare','');
      $aTemplate->SetVar('ErrorText',$aErrorText);
      $aTemplate->Parse('Error','False');
   } else {
      $aTemplate->SetVar('Error','');
      $aTemplate->Parse('Prepare','False');
   }
   PBGeneric::showTempl($aTemplate);
}

sub redirect
{
   my ($aUrl)=@_;

   print "<script>document.location='".$aUrl."';</script>\n";
}