#!/usr/bin/perl
# Copyright 1999-2025. WebPros International GmbH. All rights reserved.

use vars qw(%config);

read_config();
correct_statistics();

sub read_config {
  open FCONF, "< /etc/psa/psa.conf"
    or die "Can't open Plesk configurational file\n";
  while (<FCONF>) {
    s/\#.*$//;
    m/^\s*(\w+)\s+(.+?)\s*$/;
    next unless $1;
    $config{$1} = $2;
  }

  close FCONF;

  $config{LOGIN} = 'admin';
  $config{DBNAME} = 'psa';

  open PASSWD, "< /etc/psa/.psa.shadow"
    or die "Can't get Plesk administrator's password\n";
  $ENV{MYSQL_PWD} = <PASSWD>;
  chomp $ENV{MYSQL_PWD};
  close PASSWD;

  $config{MYSQL} = $config{MYSQL_BIN_D}.'/mysql -s -N -u'.shellArgQuote($config{LOGIN}).' -D'.$config{DBNAME};

  if (-e '/etc/SuSE-release' or -e '/etc/debian_version') {
    $config{MYSQL_SCRIPT} = $config{PRODUCT_RC_D} . '/mysql';
  } else {
    $config{MYSQL_SCRIPT} = $config{PRODUCT_RC_D} . '/mysqld';
  }

  $config{FTPSERV} = $config{PRODUCT_ROOT_D}.'/admin/bin/ftpmng';
  $config{WEBSTAT} = $config{PRODUCT_ROOT_D}.'/admin/bin/webstatmng';
  $config{LOGROT} = $config{PRODUCT_ROOT_D}.'/admin/bin/logrot_mng';

  return 0;
}

sub correct_statistics {
  my @domains;
  my $query = "SELECT d.name FROM domains d, hosting h WHERE d.id=h.dom_id AND d.htype='vrt_hst' AND h.webstat='awstats'";
  my $command = $config{MYSQL}." -e \"$query\"";
  open (QUERY, "$command |");
  while (<QUERY>) {
    if(m/^\s*([\S]+)\s*$/) {
      push @domains, $1;
    }
  }
  close QUERY;

  my @dirs = ('webstat', 'anon_ftpstat', 'ftpstat', 'webstat-ssl');

  foreach my $domain (@domains) {
    foreach my $dir (@dirs) {
        my $path = $config{HTTPD_VHOSTS_D}."/".$domain."/statistics/".$dir;
        chdir($path);
        (undef, undef, undef, undef, $mon, $year, undef, undef, undef) = gmtime(time());
        $mon++; $mon=sprintf "%02d",$mon;
        $year+=1900;
        my $date_dir = $year."-".$mon;
        if (! -d $date_dir) {
          mkdir($date_dir);
          system("mv * $date_dir > /dev/null 2>&1");
          symlink($date_dir, "current");
        }
    }
    system ($config{WEBSTAT}. " --set-configs --stat-prog=awstats --domain-name=$domain");
  }
}

sub shellArgQuote($){
  ($_) = @_;
  s/'/'\\''/g;
  return "'$_'";
}

