#!/usr/bin/perl -w

use strict ;
use vars qw( $VERSION ) ;
use Eesh qw( :all ) ;

$VERSION = '1.1' ;

=head1 NAME

rehome - Grab windows by title fragment or regular expression and rehomes them

=head1 SYNOPSIS

Fragment of title:

   rehome Terminal

A regular expression:

   rehome "/^ab.*c$/"

If you have Regexp::Shellish, you can rephrase that last one as:
   
   rehome "ab*c"

=head1 DESCRIPTION

When a window wanders off your display, rehome it.

Takes title fragments regular expressions and (if you have installed
Regexp::Shellish) shell-like wildcards.  Remember to quote the
wildcards.

=head1 AUTHOR

Barrie Slaymaker <barries@slaysys.com>

=cut

my $debug = 1 ;

eval {
   use Regexp::Shellish 0.92 qw( compile_shellish ) ;
   1 ;
} ;
my $got_shellish = ! $@ ;

print "Regexp::Shellish detected\n" if $debug && $got_shellish ;

my $re = join(
   '|',
   map {
      $_ =~ m{^/(.*)/$}
         ? $1
	 : $got_shellish
	    ? compile_shellish( $_, { anchors => 0 } )
	    : quotemeta $_
   } @ARGV
) ;

print "Regexp: $re\n" if $debug ;

e_open() ;

for ( split( /^/m, e_recv( 'window_list' ) ) ) {
   chomp ;
   my ( $id, $title ) = m{^\s*(\S*).*?:\s*(.*)} ;

   next unless $title =~ $re ;

   my $where = e_recv( "win_op $id move ?" ) ;
   chomp $where ;
   $where =~ s{.*(\d+)\D+(\d+)}{$1,$2} ;

   print "Rehoming $title from $where\n" ;
   e_send( "win_op $id move 0 0" ) ;
}