#!/usr/bin/perl

my $cmd = 1;

if($ARGV[0] && $ARGV[0] eq 'set') {
  $cmd = 2;
}

# ulozeni pozic
if($cmd == 1) {
  open(WMCTRL, "wmctrl -l -G |");
  open(WPOS, "> /tmp/wpos.txt");
  while($row = <WMCTRL>) {
    if($row =~ /^([0-9a-fx]+)\W+[-0-9]+\W+([0-9]+)\W+([0-9]+)\W+([0-9]+)\W+([0-9]+)/) {
      $winid = $1;
      $x = $2;
      $y = $3;
      $width = $4;
      $height = $5;
      $frame = `xprop -id $1 | egrep ^_NET_FRAME_EXTENTS`;
      if($frame =~ /([0-9]+),\W+([0-9]+),\W+([0-9]+),\W+([0-9]+)/) {
        $x = $x - $1;
        $y = $y - $3;
      }
      print WPOS $winid.";".$x.';'.$y.';'.$width.';'.$height."\n";
    }
  }
  close(WPOS);
  close(WMCTRL);
}
# nacteni pozic
else {
  open(WPOS, "/tmp/wpos.txt");
  while($row = <WPOS>) {
    if($row =~ /^([0-9a-fx]+);([0-9]+);([0-9]+);([0-9]+);([0-9]+)/) {
      system("wmctrl -i -r $1 -e 0,$2,$3,$4,$5");
    }
  }
  close(WPOS);
}