#!/usr/bin/perl

use strict;
use warnings;
use lib '/opt/pos/lib';
use App::POS::Config;
use Data::Dumper;
use File::Find qw( find );

my $cfg = App::POS::Config->new( file => "/opt/pos/etc/config.ini" );
my $info = $cfg->load();
my $LANG = $info->{LANG} || "";
my $skin = $LANG;

my $dir_skin = '/opt/pos/common/skins/'.$skin;
my $cur_w = "";
my $cur_h = "";

if (! -d $dir_skin) {
  die "Invalid skin: $skin\n";
}

my @t = `xrandr -q`;

for (@t) {
  next if /^\s+/;
  chop;
  next unless /\sconnected\s(\d+)x(\d+)/;
  $cur_w = $1;
  $cur_h = $2;
  last;
}

if (! $cur_w || ! $cur_h) {
  die "Can't find current resolution...\n";
}

if ($cur_w == 800 && $cur_h == 600) {
  die "Current screen resolution is 800x600, don't need to rescale...\n";
}

# clean folder before start
system("rm -rf \"$dir_skin/rescaled\" 2> /dev/null");
system("mkdir -p \"$dir_skin/rescaled\"");

find( sub {
  my $fname = $_;

  # ignore non png files
  return unless /\.png$/i;

  # ignore sub-folders in skin
  return unless $File::Find::dir eq $dir_skin;

  my( $ident ) = `identify -format "%w %h" "$File::Find::name"`;
  return unless defined $ident;

  my( $width, $height ) = split ' ', $ident;

  my $cmd = "";

  # 800 x 600 image
  if ($width >= 795 && $height >= 595) {
    $cmd = "convert \"$File::Find::name\" -resize ".$cur_w."x".$cur_h."! \"$dir_skin/rescaled/$fname\"";
  }
  else {
    my $new_pic_w = ($cur_w * $width) / 800;
    my $new_pic_h = ($cur_h * $height) / 600;
#    my $factor = $cur_w / 800 * 100;
    $cmd = "convert \"$File::Find::name\" -resize ".$new_pic_w."x".$new_pic_h."! \"$dir_skin/rescaled/$fname\"";
  }

  print STDERR $cmd."\n";
  `$cmd`;
}, ( $dir_skin ) );

