#!/usr/bin/env perl

use strict;
use warnings;

use WWW::Mechanize;
use Mojo::DOM;
use Config::General;
use Data::Dumper;

#Usage:
# sms.pl MOBILE_NO "TEXT_MESSAGE"
#
# You need to set sms.conf file in the scripts directory and fill it
# like this:
# login    LOGIN
# password PASSWORD
#
# where LOGIN and PASSWORD are your credentials to orange.pl site

my $conf = new Config::General("sms.conf");
my %config = $conf->getall;
die "No login in config file. Stopped" unless $config{login};
die "No password in config file. Stopped" unless $config{password};

my $number = $ARGV[0];
my $message = $ARGV[1];
die "No recipient number entered. Stopped" unless $number;
die "No message entered. Stopped" unless $message;

my $mech = WWW::Mechanize->new;
$mech->get("http://orange.pl");
$mech->submit_form(
    form_id => 'loginForm',
    fields => {
	'/tp/core/profile/login/ProfileLoginFormHandler.value.login' => $config{login},
	'/tp/core/profile/login/ProfileLoginFormHandler.value.password' => $config{password}
    }
  );
$mech->follow_link( text => 'SMS');

my $dom = Mojo::DOM->new;
$dom->parse($mech->content());

my $send_url = $dom->find('div[id="top-buttons"] a')->[1]->attrs('href');
$mech->get($send_url);

# Using $mech->submit_form instead is not working, so don't change
# code below!
$mech->form_name('sendSMS');
$mech->set_fields(
    '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.to' => $number,
    '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.body' => $message,
);
$mech->click();

$dom->parse($mech->content());

my $free_sms_left = $dom->find('div[id="syndication"] p span')->[1]->text;

print "Message has been sent. Free sms'es left: $free_sms_left\n";
