#!/usr/bin/perl

use strict;
use warnings;
use FindBin qw( $Bin );
use File::Copy qw( copy );
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];
}

system("disk_rw");

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

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

&commands();

&copy("$Bin/data/startup", "/root/.fluxbox/startup");
&copy("$Bin/data/startup", "/root/.fluxbox/startup.orig");
&copy("$Bin/data/xorg.conf", "/etc/X11/xorg.conf");

# touch
system("mkdir /tmp/touch") unless -d "/tmp/touch";
system("tar zxf $Bin/../software/eGTouch.tar.gz --directory=/tmp/touch");
my $touch_folder = `ls /tmp/touch | tail -1`;
chop($touch_folder);

my $exp = Expect->new();

chdir("/tmp/touch/$touch_folder");
$exp->spawn("sh /tmp/touch/$touch_folder/setup.sh", ());

$exp->expect(30,
  [
    qr/Yes, I agree/ => sub {
      my $exp = shift;
      $exp->send("Y\n");
      exp_continue;
    },
  ],
  [
    qr/PS2/ => sub {
      my $exp = shift;
      # 1 - RS212, 2 - USB, 3 - PS2
      $exp->send("1\n");
      exp_continue;
    },
  ],
  [
    qr/key to continue/ => sub {
      my $exp = shift;
      $exp->send("\n");
      exp_continue;
    },
  ],
#  [
#    qr/patched kernel/ => sub {
#      my $exp = shift;
#      $exp->send("Y\n");
#      exp_continue;
#    },
#  ],
  [
    qr/Default/ => sub {
      my $exp = shift;
      $exp->send("1\n");
      exp_continue;
    },
  ],
);

&copy("$Bin/data/machine_calibrate", "/opt/bin/machine_calibrate");
system("chmod 755 /opt/bin/machine_calibrate");

&copy("$Bin/data/grub", "/etc/default/grub");
system("update-grub");

# this is here to make sure the eGalax installed don't make wrong stuff in rc.local
&copy("$Bin/data/rc.local", "/etc/rc.local");
system("chmod 755 /etc/rc.local");

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


