#!/usr/bin/env perl

use strict;
use warnings;
use feature "say";

my $EMPTY_REF = '0' x 40;

sub get_origin_info {
    my $origin_info = qx(git remote show -n origin);
    if($origin_info =~ m{^\s*Fetch\s+URL:.*github[.]com/([^/]+)/([^/]+)$}m) {
        return (
            $1, # username
            $2, # password
        );
    } else {
        return;
    }
}

sub get_fork_info {
    my ( $username, $repo_name ) = @_;

    $repo_name =~ s/[.]git$//; # remove .git suffix

    my $gh    = Net::GitHub::V3->new;
    my $repos = $gh->repos;
    $repos->set_default_user_repo($username, $repo_name);

    my $repo = $repos->get;
    return unless $repo->{'fork'};
    return $repo->{'parent'};
}

sub is_clone_operation {
    my ( $previous_ref ) = @ARGV;

    return $previous_ref eq $EMPTY_REF;
}

my $ok = eval {
    require Net::GitHub::V3;
};
unless($ok) {
    warn "Could not load Net::GitHub::V3; exiting\n";
    exit 0;
}

$ok = eval {
    require LWP::Protocol::https;
};
unless($ok) {
    warn "Could not load LWP::Protocol::https; exiting\n";
    exit 0;
}

exit 0 unless is_clone_operation; # we don't care unless it's a clone

my ( $username, $repo_name ) = get_origin_info;

exit 0 unless $username; # not a Github repo

my $fork_info = get_fork_info($username, $repo_name);

exit 0 unless $fork_info; # we don't care if this isn't a fork

my $url = $fork_info->{'git_url'};
$url =~ s{^(git|https)://github[.]com/}{github:};

system 'git', 'remote', 'add', 'base', $url;
