#!/usr/bin/perl

use warnings;
use strict;

use Getopt::Long;
use Net::GitHub;
use Term::ReadLine;

=for :stopwords

OAuth oauth

=head1 NAME

github-oauth - Generate GitHub OAuth2 token

=head1 SYNOPSIS

 github-oauth [note-text]

=head1 DESCRIPTION

B<dpt github-oauth> can be used for obtaining an OAuth2 token for
authenticating to GitHub services without the need to enter your password on
every request. The reason for this script is to allow you to populate the
C<DPT_GITHUB_OAUTH> setting in F<dpt.conf> easily.

An alternative method for obtaining the token is to use the GitHub web
interface, Applications-E<gt>Personal Access Tokens.

The token obtained with this program is authorized only for reporting issues.

The only supported argument, I<note-text>, is a short note associated with
the token. It is used for easy distinguishing different tokens and their
purpose. If not specified, the string C<pkg-perl-tools on host $HOSTNAME> is
used, where C<$HOSTNAME> is obtained via L<Sys::Hostname>.

The GitHub user name and password are prompted for and can't be supplied as
command-line options.

=cut


my $term = Term::ReadLine->new('github-oauth');

my $gh_user = $term->readline( 'GitHub user name >', $ENV{USER} );
die "GitHub user name is required\n" unless $gh_user;

my $gh_pass = $term->readline( 'GitHub password (not hidden /!\) >', '' );
die "GitHub password is required\n" unless $gh_pass;

my $note = $ARGV[1];

unless ($note) {
    require Sys::Hostname;
    my $host = Sys::Hostname::hostname();
    $note = "pkg-perl-tools";
}

my $gh = Net::GitHub->new(    # Net::GitHub::V3
    login => $gh_user,
    pass  => $gh_pass,
);

my $oauth = $gh->oauth;
my $o = $oauth->create_authorization(
    {   scopes => ['public_repo'],
        note  => $note,
    }
);

print <<EOF;
The following line may be added to ~/.config/dpt.conf to allow dpt
to identify as yourself before GitHub:

 DPT_GITHUB_OAUTH=$o->{token}

EOF

=head1 AUTHOR

Damyan Ivanov <dmn@debian.org>

=head1 LICENSE AND COPYRIGHT

Copyright 2014 Damyan Ivanov.

This program is free software; you can redistribute it and/or modify it
under the terms of either: the GNU General Public License as published
by the Free Software Foundation; or the Artistic License.

See http://dev.perl.org/licenses/ for more information.

=cut
