#!/usr/local/bin/perl -w
###########################################
# readme-upd - Update the README on Github
# Mike Schilli, 2015 (m@perlmeister.com)
###########################################
use strict;
use Net::GitHub;
use YAML qw( LoadFile );
use Digest::SHA1 qw( sha1_hex );

my $gh_conf = (glob "~")[0] . "/.githubrc";

my $gh = Net::GitHub->new( access_token => 
  LoadFile( $gh_conf )->{ token }
);

$gh->set_default_user_repo( 
  "mschilli", "apitest" );
my $gdata = $gh->git_data();

my $head;

for my $ref ( @{ $gdata->refs() } ) {
  if( $ref->{ ref } eq 
      "refs/heads/master" ) {
    $head = $ref->{ object }->{ sha };
    last;
  }
}

die "Head not found" if !defined $head;

my $commit_old = $gdata->commit( $head );
my $tree_old = 
  $commit_old->{ tree }->{ sha };

my $content = "Updated by script $0.";

my $tree = $gdata->create_tree( { 
  tree => [ { 
    path => "README", mode => "100644",
    type => "blob",   content => $content,
  } ],
  base_tree => $tree_old,
} );

my $commit = $gdata->create_commit( {
  message => "Updated via API",
  author => {
    name =>  "Mike Schilli",
    email => 'm@perlmeister.com',
    date =>  "2011-11-11T11:11:11+08:00",
  },
  parents => [ $head ],
  tree => $tree->{ sha },
} );

$gdata->update_ref( "heads/master", 
  { sha => $commit->{ sha } } );
