#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use File::Slurp qw( read_file write_file );
use FindBin qw( $Bin );
use File::Copy qw( copy move );
use Expect;
use lib "$Bin/../software";
use Common qw( commands );

my @path = split /\//, $Bin;
my $pen_path = "";

if ($path[1] eq 'opt') {
  $pen_path = "/".$path[2]."/".$path[3];
}
elsif ($path[1] eq 'var') {
  $pen_path = "/".$path[3]."/".$path[4];
}
else {
  $pen_path = "/".$path[1]."/".$path[2];
}

my @x_pid = `ps xa | grep X | grep nolisten | grep -v grep`;

if (scalar @x_pid) {
  die "Must stop X first...\n";
}

print "Want to install graphical display? [y/n]\n";
my $ans = <STDIN>;
$ans =~ s/\n//g;

my %keys_to_ignore = (
  AUTO_RELOCATE_WINDOWS          => 1,
  SCREEN_RESCALE_W               => 1,
  SCREEN_RESCALE_H               => 1,
  USE_GRAPHICAL_CUSTOMER_DISPLAY => 1,
);

my @lines = read_file("/opt/pos/etc/config.ini");
my @new_lines = ();

foreach my $l (@lines) {
  my @toks = split /=/, $l;
  push @new_lines, $l unless exists $keys_to_ignore{$toks[0]};
}

if (uc($ans) eq 'Y') {
  open(F, "> /tmp/$$.ini");
  print F "AUTO_RELOCATE_WINDOWS=1\n";
  print F "SCREEN_RESCALE_W=1024\n";
  print F "SCREEN_RESCALE_H=768\n";
  print F "USE_GRAPHICAL_CUSTOMER_DISPLAY=1\n";
  close(F);

  write_file( "/tmp/$$.ini", { append => 1 },  @new_lines );
  move( "/tmp/$$.ini", "/opt/pos/etc/config.ini" );

  &copy("$Bin/data/startup", "/root/.fluxbox/startup");
  &copy("$Bin/data/display.sh", "/opt/bin/display.sh");
  system("chmod 755 /opt/bin/display.sh");
  &copy("$Bin/data/display.sh.orig", "/opt/bin/display.sh.orig");
  &copy("$Bin/data/machine_calibrate.display", "/opt/bin/machine_calibrate");
  &copy("$Bin/data/config.xml", "/opt/pos/common/addons/graphical_display/config.xml");
}
else {
  write_file( "/tmp/$$.ini", { append => 0 },  @new_lines );
  move( "/tmp/$$.ini", "/opt/pos/etc/config.ini" );
  &copy("$Bin/data/startup", "/root/.fluxbox/startup");
  &copy("$Bin/data/machine_calibrate", "/opt/bin/machine_calibrate");
}

system("chmod 755 /opt/bin/machine_calibrate");
&copy("$Bin/data/rc.local", "/etc/rc.local");
&copy("$Bin/data/grub", "/etc/default/grub");
system("update-grub");

&commands();

system("touch /.configured");
system("reboot");

