#!/usr/bin/perl
use v5.10.0;
use strict;
use warnings;
use autodie;
use Exobrain::Config 1.01;
use Net::Twitter;

# PODNAME: exobrain-twitter-auth
# ABSTRACT: OAuth with twitter from the command-line
our $VERSION = '1.02'; # VERSION


# TODO: Make a generalised exobrain config sript that calls this.

say "\n\nHey there, we'll need to start by getting an API key from twitter.\n";
say "Head over to: https://apps.twitter.com/app/new\n";
say "You need only fill in the required fields there.";
say "Alternatively, if you already have a registered app, you can use that.";

say "\nOnce done, you'll need to provide the API key and secret.";
say "These are not shared with anyone.";

print "\nAPI key: ";
chomp(my $consumer_key = <STDIN>);

print "\nAPI secret: ";
chomp(my $consumer_secret = <STDIN>);

unless ($consumer_key and $consumer_secret) {
    die "I need both the key and secret to proceed. Halting.\n";
}

say "\n\nThanks! Authing with twitter...\n";

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

say "\n----------------------------------------------\n";

say "Great! Now, to complete the auth, visit this URL, and enter the PIN...\n";

say $nt->get_authorization_url;

print "\nPIN: ";

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

my($access_token, $access_token_secret, $user_id, $screen_name) = $nt->request_access_token(verifier => $pin);

say "\n\nThanks \@$screen_name!";

my $config = 
    "[Components]\n" .
    "Twitter=$VERSION\n\n" .

    "[Twitter]\n" .
    "consumer_key        = $consumer_key\n" .
    "consumer_secret     = $consumer_secret\n" .
    "access_token        = $access_token\n" .
    "access_token_secret = $access_token_secret\n"
;

my $filename = Exobrain::Config->write_config('Twitter.ini', $config);

say "\n\nConfig written to $filename. Have a nice day!";

__END__

=pod

=head1 NAME

exobrain-twitter-auth - OAuth with twitter from the command-line

=head1 VERSION

version 1.02

=head1 SYNOPSIS

    $ exobrain-twitter-auth

=head1 DESCRIPTION

This command-line utility handles the set up of Twitter
components for the Exobrain framework. You need only run
it once, and it will walk you through the install process.

This program does not change any files on your system,
you will need to copy-and-paste the results into your
F<~/.exobrainrc> file at the end of the process.

=head1 AUTHOR

Paul Fenwick <pjf@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2014 by Paul Fenwick.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
