#!/usr/bin/perl

use lib "$ENV{HOME}/perl5/lib/perl5";

use Net::Twitter;

our $consumer_key    = q(things);
our $consumer_secret = q(andStuff);

my $nt = Net::Twitter->new
  (
   traits          => ['API::REST', 'OAuth'],
   consumer_key    => $consumer_key,
   consumer_secret => $consumer_secret,
  );

# You'll save the token and secret in cookie, config file or session database
my($access_token, $access_token_secret) = restore_tokens();
if ($access_token && $access_token_secret)
  {
    $nt->access_token($access_token);
    $nt->access_token_secret($access_token_secret);
  }

unless ( $nt->authorized )
  {
    # The client is not yet authorized: Do it now
    print "Authorize this app at ", $nt->get_authorization_url, " and enter the PIN#\n";

    my $pin = <STDIN>; # wait for input
    chomp $pin;

    my($access_token, $access_token_secret, $user_id, $screen_name) = $nt->request_access_token(verifier => $pin);
    save_tokens($access_token, $access_token_secret); # if necessary
  }

print "Done\n";
exit( 0 );

sub restore_tokens
  {
    open my $fh, '<', ".oauth" or die qq(failed to create file; $!);
    my($access_token, $access_token_secret) = map
      {
        chomp;
        s/^[^:]+:// if defined and length;
        $_
      } <$fh>;
    close $fh;
    return ($access_token, $access_token_secret);
  }

sub save_tokens
  {
    die qq(Not enough arguments to save_tokens) unless @_ > 1;
    my($access_token, $access_token_secret) = @_;
    die qq(Access token is required) unless $access_token;
    die qq(Access token secret is required) unless $access_token_secret;
    open my $fh, '>', ".oauth" or die qq(failed to create file; $!);
    my $ofh = select $fh;
    print "token:$access_token\n";
    print "secret:$access_token_secret\n";
    select $ofh;
    close $fh;
  }

__END__
