#!/usr/bin/perl -W
#Usage:  vcal.pl -?
#Version: 0.4
use Getopt::Std;
use CGI qw(:all *table);
use CGI::Carp qw(fatalsToBrowser);

my(%opts);
getopts('f:i:t:m:s?hp',\%opts);

#Set the following to "1" if you want to send mail, otherwise, set to "0" and just the code will be printed out.
$SENDMAIL=$opts{'s'} || 1;

#Set the following to the mail server
$MAILHOST=$opts{'m'} || 'YOUR MAIL SERVER HERE';

#Set the following to the username on the mail server
$FROM=$opts{'f'} || 'YOUR MAIL SERVER EMAIL ADDRESS HERE';

#Set the following to a CSV list of addresses to send the mail to
$TO=$opts{'t'} || param('to') || 'YOUR CELL PHONES EMAIL ADDRESS HERE';
$TO=~/.*?([\w\@\.\-]+).*?/;
$TO=$1;

#Uncomment the following to use Blat for your MTA (If you are on a Windows machine)
#Set the following to the location of your mail program, Blat (www.blat.net)
#$BLAT="C:\\blat";
#$MAILCOMMAND="|$BLAT - -server $MAILHOST -f $FROM -s \"\" -t $TO -q";

#uncomment the following to use Sendmail for your MTA (If you are on a Unix machine)
#Set the following to your sendmail location
$SENDMAILPATH="/usr/sbin/sendmail";
$MAILCOMMAND="| $SENDMAILPATH $TO";

#Set the following to the number of seconds to sleep between consecutive sends when a file is used
$SLEEPTIME="30";

#You are done editing

if($opts{'?'} or $opts{'h'}){
  &usage();
}

if($opts{'i'}){
  open(DAT,"<$opts{'i'}") or die "Can't open $opts{'i'}: $!";
}

$continue=1;

while($continue){
  if($opts{'i'}){
    if(eof(DAT)){close(DAT);exit;}
    sleep($SLEEPTIME);
    chomp($data=<DAT>);
    ($category,$dtstartdate,$dtstarttime,$description,$dtalarmdate,$dtalarmtime)=split(/\s*,\s*/,$data);
    if($opts{'p'}){
      print "Send '$category,$dtstartdate,$dtstarttime,$description,$dtalarmdate,$dtalarmtime' =>";
      $input=<STDIN>;
    }    
  }
  else{
    if(!$ENV{'HTTP_USER_AGENT'}){
      binmode(STDIN,":crlf");	#CGI.pm calls binmode on STDIN
      print "\nEnter Category (PHONE CALL, SPECIAL OCCASION, MEETING, MISCELLANEOUS) (CTRL+C to quit): ";
      chomp($category=<STDIN>);
      print "\nEnter Start Date (YYYYMMDD): ";
      chomp($dtstartdate=<STDIN>);
      print "Enter Start Time (HHMMSS): ";
      chomp($dtstarttime=<STDIN>);
      print "Enter Description: ";
      chomp($description=<STDIN>);
      print "Enter Alarm Date (YYYYMMDD): ";
      chomp($dtalarmdate=<STDIN>);
      print "Enter Alarm Time (HHMMSS): ";
      chomp($dtalarmtime=<STDIN>);
    }
    else{
      if(param(todo) eq 'Send' and param('category') ne "(Select One)"){
        $category=param('category');
        $dtstartdate=param('dtstartdate');
        $dtstarttime=param('dtstarttime');
        $dtalarmdate=param('dtalarmdate');
        $dtalarmtime=param('dtalarmtime');
        $description=param('description');
	   print header(), "Sending to $TO ....",br(),"<pre>\n";
      }
      else{
        $script=<<END;
function today(){
  today=new Date();
  month=today.getMonth()+1;
  if(month <= 9){month="0"+month.toString();}
  else{month=month.toString();}
  thedate=String(today.getFullYear())+month+String(today.getDate());
  document.vcal.dtstartdate.value=thedate;
}
function setthedate(){
  document.vcal.dtalarmdate.value=document.vcal.dtstartdate.value;
}
function birthday(){
  choice=document.vcal.category[document.vcal.category.selectedIndex].text;
  if(choice=="SPECIAL OCCASION"){
    document.vcal.dtstarttime.value="235959";
  }
  else{
    document.vcal.dtstarttime.value="";
  }
}
END
        print header(),
			start_html({-script=>$script}),
			h1('The Cell Phone VCard Mailer'),
			"This code is known to work with: ",
			br(),
			"&nbsp;",
			i(b("Providers:"),"AT&T (\@mobile.att.net), US Cellular (\@uscc.textmsg.com)."),
			" ",
			br(),
			"&nbsp;",
			i(b("Phones:"),u("Nokia:")," 5160, 5165, 6160, 6165, 8260"),
			p(),
			start_form({-name=>'vcal'}),
			b("Enter Your Cell Phone Email Address:"),
			" ",
			textfield({-name=>'to'}),
			br(),
			b("Enter the category:"),
			" ",
			popup_menu({-name=>'category',
					-values=>['(Select One)','SPECIAL OCCASION','MEETING','MISCELLANEOUS','PHONE CALL'],
					-onChange=>"birthday();"}),
			br(),
			i("For 'Special Occasion', Birthday, or Anniversary the date should be the date of the event and the time should be '235959'."),
			br(),
			i("Special Occasion alarms are only recurring if they are in the future (after right now)."),
			br(),
			i("For 'Phone Call' the message should be the phone number to call"),
			br(),
			"Event Date ",
			i("(YYYYMMDD)",a({href=>"javascript:today();"},"today")),
			":",
			textfield({-name=>'dtstartdate'}),
			"Event Time ",
			i("(HHMMSS)"),
			":",
			textfield({-name=>'dtstarttime'}),
			br(),
			"Alarm Date ",
			i("(YYYYMMDD)",a({-href=>"javascript:setthedate();"},"same")),
			":",
			textfield({-name=>'dtalarmdate'}),
			"Alarm Time ",
			i("(HHMMSS)"),
			":",
			textfield({-name=>'dtalarmtime'}),
			br(),
			b("Name/Meeting/Message/Phone Number:"),
			textfield({-name=>'description'}),
			reset(),
			" ",
			submit({-name=>'todo',-value=>'Send'}),
			end_form(),
			p(),
			a({-href=>"mailto:bsa\@pobox.com,%61%64%61%6d%40%62%75%6d%70%2e%75%73 ? subject=VCal Comments"},i("E-Mail Comments about VCal")),
			p(),
			"Written by: ",
			a({-href=>"mailto:bsa\@pobox.com"},"Brad Andersen"),
			" and ",
			a({-href=>"mailto:%61%64%61%6d%40%62%75%6d%70%2e%75%73"},"Adam Bumpus");
        exit;
      }
    }
  }

  $string="BEGIN:VCALENDAR\r\n";
  $string.="BEGIN:VEVENT\r\n";
  $string.="CATEGORIES:$category\r\n" if $category;
  $string.="DTSTART:${dtstartdate}T${dtstarttime}\r\n" if $dtstartdate and $dtstarttime;
#DESCRIPTION or SUMMARY
  $string.="SUMMARY:$description\r\n" if $description;
#AALARM or DALARM
  $string.="DALARM:${dtalarmdate}T${dtalarmtime}\r\n" if $dtalarmdate and $dtalarmtime;
  $string.="END:VEVENT\r\n";
  $string.="END:VCALENDAR\r\n";
  print "\nGenerating VCalendar:\n$string\n";


#My limit for text messages is 150 char, this leaves me with room for return address and such

  #Generate a random number to use for message id
  $ID=rand(255);

  #Convert the VCard to Hex
  $vcard="";
#I've learned a new trick so I'm going to use it.  We use substr like splice.
#  for($i=0;$i<length($string);$i++){
#    $vcard.=sprintf("%2.2X",ord(substr($string,$i,1)));
#  }
  while(length($string)){
    $vcard.=sprintf("%2.2X",ord(substr($string,0,1,"")));
  }
  @string=();
  #break into chunks of 80 characters and store in an array
  while(length($vcard)>80){
    push(@string,substr($vcard,0,80,""));
  }
  push(@string,$vcard);

  #Process each 80 character chunk and send 95 character messages
  for($i=0;$i<scalar(@string);$i++){
    $message="//SCKL23F523F5";
    $message.=sprintf("%2.2X%2.2X%2.2X ", $ID ,scalar(@string),$i+1);
    $message.=$string[$i];

    print "\nThe Nokia Smart Messaging VCalendar is:\n\n$message\n";

    if($SENDMAIL==1){
      print "\nMailing output to $TO\n";
      open(OUT,"$MAILCOMMAND") or die "Can't open mailer: $!";
      print OUT "$message\n";
      close(OUT);
    }
  }
  if($ENV{'HTTP_USER_AGENT'}){
     print "\nSent.</pre>",
	p(),
	"Enter ",
	a({-href=>"javascript:history.go(-1)"},"another?"),;
     last;
  }
}
exit;

sub usage{
print <<END;
Usage: $0 [options]

Options		Description
-i filename		A CSV input file of "category,date,time,description,alarm date, alarm time" to send
-t phone email	Email address of the phone you want to send the card to
-f from email	Valid email address on MTA server (From: address)
-m server		IP Address or Hostname of MTA server
-s			Send mail
-p			Prompt during bulk send after each line
-?			Print this message
-h			Print this message

(This can be run as a CGI program, if the To: field is left blank then the hard
  coded To: address will be used)

(Most of these can be hardcoded into this file)

END
exit;
}



