#!/usr/local/bin/perl -w
###########################################
# oauth - Init Tumblr Oauth Tokens
# Mike Schilli, 2013 (m@perlmeister.com)
###########################################
use strict;
use Storable;
use WWW::Tumblr::Authentication::OAuth;
use Mojolicious::Lite;
use YAML qw( DumpFile );
use Sysadm::Install qw( :all );

my( $home ) = glob "~";
my $cfg_file     = "$home/.tumblr.yml";
my $local_url    = "http://localhost:8082";
my $consumer_key = "XXX";
my $secret_key   = "YYY";

my $tumblr_oauth = 
   WWW::Tumblr::Authentication::OAuth->new(
  consumer_key => $consumer_key,
  secret_key   => $secret_key,
  callback     => "$local_url/callback",
)->oauth_tools;

@ARGV = (qw(daemon --listen), $local_url);

###########################################
get '/' => sub {
###########################################
  my( $self ) = @_;

  $self->stash->{login_url} =
    $tumblr_oauth->authorize_url();

} => 'index';

###########################################
get '/callback' => sub {
###########################################
  my ( $self ) = @_;

  my $oauth_token    = 
    $self->param( "oauth_token" );
  my $oauth_verifier = 
    $self->param( "oauth_verifier" );

  $tumblr_oauth->oauth_token( 
      $oauth_token );
  $tumblr_oauth->oauth_verifier( 
      $oauth_verifier );

  DumpFile( $cfg_file, {
    oauth_token    => $oauth_token,
    oauth_verifier => $oauth_verifier,
    consumer_key   => $consumer_key,
    secret_key     => $secret_key,
    token => $tumblr_oauth->token(),
    token_secret => 
      $tumblr_oauth->token_secret(),
  } );

  $self->render( 
    text => "Tokens saved in $cfg_file.",
            layout => 'default' );
};

app->start();

__DATA__
###########################################
@@ index.html.ep
% layout 'default';
<a href="<%= $login_url %>"
>Login on Tumblr</a>

@@ layouts/default.html.ep
<!doctype html><html>
  <head><title>Token Fetcher</title></head>
    <body>
      <pre>
      <%== content %>
      </pre>
    </body>
</html>
