#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long;
use Pod::Usage;

use Carp qw( croak );
use English qw( -no_match_vars );
use IPC::Run qw( run );
use Browser::Open qw( open_browser );

use EPFL::Service::Open qw( getService );

=head1 NAME

epfl-service-open

=head1 DESCRIPTION

Open the EPFL website (service) associated with the Git repository.

=head1 VERSION

Version 1.03

=head1 USAGE

  epfl-service-open --help

  epfl-service-open

=cut

our $VERSION = '1.03';

my ($help);

GetOptions( 'help' => \$help ) || pod2usage(2);

if ($help) {
  pod2usage(1);
  exit 0;
}

my $isGitRepo = p_isGitRepository();

if ( $isGitRepo =~ m/true/xms ) {
  my $gitRemoteUrl = p_getGitRemote();
  my $serviceUrl   = getService($gitRemoteUrl);
  if ( defined $serviceUrl ) {
    my $ok = open_browser($serviceUrl);
  }
  else {
    print "Project not handled\n" or croak "Couldn't write: $OS_ERROR";
  }
}

# Are we in a git repo?
sub p_isGitRepository {
  my $isGit;
  run [ 'git', 'rev-parse', '--is-inside-work-tree' ], '>', \$isGit;
  return $isGit;
}

# Get remote url of repo
sub p_getGitRemote {
  my $gitRemoteUrl;
  run [ 'git', 'ls-remote', '--get-url' ], '>', \$gitRemoteUrl;
  return $gitRemoteUrl;
}

=head1 AUTHOR

William Belle, C<< <william.belle at gmail.com> >>

=head1 BUGS AND LIMITATIONS

Please report any bugs or feature requests here L<https://github.com/epfl-devrun/epfl-service-open/issues>.
I will be notified, and then you'll automatically be notified of progress on
your bug as I make changes.

=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc epfl-service-open

You can also look for information at:

=over 4

=item * AnnoCPAN: Annotated CPAN documentation

L<http://annocpan.org/dist/EPFL-Service-Open>

=item * CPAN Ratings

L<http://cpanratings.perl.org/d/EPFL-Service-Open>

=item * Search CPAN

L<http://search.cpan.org/dist/EPFL-Service-Open/>

=back

=head1 LICENSE AND COPYRIGHT

Original work Copyright ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE,
Switzerland, VPSI, 2018.

Modified work Copyright William Belle, 2018.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    L<http://www.apache.org/licenses/LICENSE-2.0>

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

1;
