#!/usr/bin/perl

use strict;
use warnings;
use File::Copy qw( copy );
use POSIX qw( strftime );
use FindBin qw( $Bin );
use Data::Dumper;

my $time_str = &strftime("%Y%m%d_%H%M%S", localtime);

my $dev = "";
my $device = `dmesg | grep "DisplayLink USB device" | tail -1`;

if ($device) {
  chop($device);
  my( $tmp ) = $device =~ /\/dev\/(.*?)\s/;
  $tmp ||= "";
  $dev = "/dev/$tmp" if $tmp;
}

if (! $dev) {
  print STDERR "DisplayLink USB device NOT FOUND. Make sure it's connected...\n";
  exit;
}

# keep graphical display resolution ok
if (-e "/opt/files/sam4s_spt4000/fonts.conf" && ! -e "/root/.fonts.conf") {
  copy("/opt/files/sam4s_spt4000/fonts.conf", "/root/.fonts.conf");
}

system("disk_rw");

print STDERR "DisplayLink USB device FOUND IN $dev\n";

if (! -e "/etc/X11/xorg.conf") {
  print STDERR "/etc/X11/xorg.conf NOT FOUND! CREATE IT FIRST...\n";
  exit;
}

my $xorg_has_it = `cat /etc/X11/xorg.conf | grep DisplayLinkScreen`;

if ($xorg_has_it) {
  print STDERR "DisplayLinkScreen IS ALREADY INSTALLED IN /etc/X11/xorg.conf, GENERATE A NEW ONE FIRST\n";
  exit;
}

my $xorg_block = `cat \"$Bin/xorg_block.conf\"`;
$xorg_block =~ s/#DEVICE#/$dev/g;

my $xorg = `cat /etc/X11/xorg.conf`;
$xorg =~ s/Section \"ServerLayout\".*?EndSection//s;

my $has_eeti = `cat /etc/X11/xorg.conf | grep EETI | grep -v grep`;
chop($has_eeti);

my $eeti_str = "";

if ($has_eeti) {
  $eeti_str = "  InputDevice \"EETI\" \"SendCoreEvents\"\n";
}

$xorg = "Section \"ServerLayout\"\n".
  "  Identifier     \"X.org Configured\"\n$eeti_str".
  "  Screen  1      \"DisplayLinkScreen\" 0 0\n".
  "  Screen  0      \"Screen 0\" RightOf \"DisplayLinkScreen\"\n".
  "  Option         \"Xinerama\" \"Off\"\n".
  "  InputDevice    \"Mouse0\" \"CorePointer\"\n".
  "  InputDevice    \"Keyboard0\" \"CoreKeyboard\"\n".
  "EndSection\n".$xorg.$xorg_block;

&copy("/etc/X11/xorg.conf", "/etc/X11/xorg.conf.$time_str");
open(F, "> /etc/X11/xorg.conf");
print F $xorg;
close(F);

print STDERR "DONE! RESTART XORG...\n";

system("killall -9 Xorg");

__END__

Section "ServerLayout"
  Identifier     "X.org Configured"
  Screen      0  "Screen0" 0 0
  Screen      1  "Screen1" RightOf "Screen0"
  Screen      2  "Screen2" RightOf "Screen1"
  InputDevice    "Mouse0" "CorePointer"
  InputDevice    "Keyboard0" "CoreKeyboard"
EndSection

Section "ServerLayout"
  Identifier     "X.org Configured"
  Screen  1      "DisplayLinkScreen" 0 0
  Screen  0      "Screen 0" RightOf "DisplayLinkScreen"
  Option         "Xinerama" "Off"                      # aqui
  InputDevice    "Mouse0" "CorePointer"
  InputDevice    "Keyboard0" "CoreKeyboard"
EndSection

