#!/usr/bin/perl -w
#
# read_calls.pl
# 
# Synopsis:
# Script is run as a service daemon. It connects to the Fritz!Box Fon Ata
# (port 1012) and receives the calling string (number of the party calling 
# in). This number is passed on to another program. I.e. this could be an 
# Jabber client or a "look who called list".
# 
# Requirements:
# - must be able to reach tcp port 1012 on your FB
# - activate call monitor on FB by dialing #96*5*
# - required perl package
#
# Licence: GPL2
#
# History:
# ver. 0.1 - 20060401 - Lars G. Sander, Zuerich
# First public release.
# ver. 0.2 - 20060510 - Ulrich Dangel <fritzbox@spamt.net>
# Added telefon book support
# To Do:
# - beefed up security?
# - proxy functionality
# - additionally monitor calls OUT
use IO::Socket;
use strict;

# your fritz box (ip or hostname)
my $FRITZBOX="fritz.box";
my $TELEFONBUCH="$ENV{HOME}/doc/addressbook";
my $EXTPRO="/usr/bin/X11/xmessage";
#-------- NO USER SERVICABLE PARTS BELOW -------#


sub read_book {
    my %book = ();
    open(IN, "<", $TELEFONBUCH) || return ();
    while(<IN>){
        chomp;
        my @elements = split(":",$_);
        $book{$elements[0]}=$elements[1];
    }
    close(IN);
    return %book;
}


my %book = &read_book;

my $sock = new IO::Socket::INET (
        PeerAddr => $FRITZBOX,
        PeerPort => '1012',
        Proto => 'tcp'
        );
        die "Could not create socket: $!\n" unless $sock;
    
while(<$sock>) {
        if ($_ =~ /RING/){
                my @C = split(/;/);
                my $nr="";
                if (exists($book{$C[3]})) {
                    $nr=$book{$C[3]};
                } else {
                    $nr=$C[3];
                }
                my @args = ($EXTPRO, "Anruf: ", $nr);
                system(@args); 
        }
}
