#!/usr/pkg/bin/perl -w
#
# Y(aho)oSucker Prototype 37
# Yahoo Mail Fetcher
#
# Copyright Dirk Diggler & Som One 1981-2002. All rides reserved.
# Coded by Som One and Pierrot Lunaire (French version)
# Redistribution and use, with or without modification,
# is permitted in the sense of GDWYWL
# (GeneralDoWhateverYouWantLicense)
# -z3r0-

use strict;
no utf8;

my $YS_path;
BEGIN {
    $YS_path = $0;

    # Let's resolve the link thing...
    while (-l $YS_path) {
        my $tmp_lnk = readlink($YS_path);

	# Do we handle an absolute or a relative link?
        if ($tmp_lnk !~ /^\//) {
                my $lnk_name = `basename $YS_path`;
                chomp($lnk_name);
                $YS_path =~ s/$lnk_name$//g;
                $YS_path = $YS_path.$tmp_lnk;
        }
        else {
                $YS_path = $tmp_lnk;
        }
    }

    $YS_path =~ s/YoSucker$//;
    eval "use lib '${YS_path}../lib';
          use sputnik;
          ";
    die "Cannot find sputnik\.pm or its dependencies.\n"  if ($@);
}

# Lets see if there is a local configuration in ~/.yosucker directory
my $homedir = ($ENV{HOME} || $ENV{LOGDIR});
my $lockfile;
my $confpath;
if (-d "$homedir/.yosucker") {
	print "Using LOCAL configuration.\n";
	$confpath = $homedir."/.yosucker";
	$lockfile = $homedir."/.yosucker-lock";
}
else {
        print "Using GLOBAL configuration.\n";
	$confpath = ${YS_path}."../conf";
        $lockfile = $YS_path."../.yosucker-lock";
}

# Lets check for the lockfile - we don't want see multiple YoSuckers
# running at the same time, do we?
if (-e "$lockfile") {
	print "YoSucker: Another YoSucker is already running. Exiting...\n";
	die "See docs/FAQ for more info.\n";
}

# Read account configuration files
my (@accounts) = `ls -1 $confpath\/*\.conf 2>/dev/null` 
	or die "YoSucker: Cannot find any configuration file\!\n";

# Catch Control-C (we need to remove the lockfile if we Ctrl-C exit)
$SIG{INT} = \&die3;

# Create the lockfile
system("touch $lockfile 2>/dev/null") == 0 
	or die "Cannot create a lock file. Wrong permissions? Exiting...\n";

# Fetch messages for all acounts
foreach (@accounts) {
	chomp;
        my $SuckIt = Sucker->new($YS_path, $lockfile);
	$SuckIt->load_config($_);
	$SuckIt->load_head_translations($confpath);
	$SuckIt->login;
}

# Lets release the filelock
unlink "$lockfile" or warn "Cannot delete the lockfile\!\n";

exit;

# Remove lockfile and die
sub die3 {
  $SIG{INT} = 'DEFAULT';
  unlink "$lockfile" if (-e "$lockfile");
  die "\nCaught a Ctrl-C signal. Exiting...\n";
}
