package Umegaya;

use Mouse;

has 'url' => (is => 'rw', isa => 'Str');

sub download_command {
    my $self = shift;
    my $file = shift;
    my $command = $self->url; # Starting with the URL, build a command.
    # Use svn cat for packages hosted in Subversion.
    if ($command =~ /^svn/) {
        $command .= '/' unless $command =~ m(/$);
        $command = "svn cat ${command}debian/$file";
        return $command;
    }
    # Download through gitweb for packages hosted on Alioth.
    if ($command =~ m,^git://(?:git|anonscm).debian.org,) {
        $command =~ s,^git://(?:git|anonscm).debian.org/g?i?t?/?(.*),http://anonscm.debian.org/gitweb/?p=$1;a=blob_plain;f=debian/$file;hb=HEAD,;
        $command = qq(curl --fail --silent "$command");
        return $command;
    }
    # GitHub
    if ($command =~ m,://github.com/,) {
        $command =~ m,://github.com/([A-Za-z0-9\+\-\.]+)/([a-z0-9\+\-\.]+).git$,;
        $command = "curl --fail --silent https://raw.github.com/$1/$2/master/debian/$file";
        return $command;
    }
    # Try git archive for other git-hosted packages.
    if ($command =~ /^git/) {
        $command = "git archive --remote=$command HEAD:debian $file | tar --extract --file - --to-stdout";
        return $command;
    }
    die "Could not guess command for " . $self->url;
}

sub guess_package {
    my $self = shift;
    foreach my $guess (
        # Debian Med
        "svn://svn.debian.org/debian-med/trunk/packages.*/([a-z0-9\+\-\.]+)/trunk",
        # Debichem
        "svn://svn.debian.org/s?v?n?/?debichem/unstable/([a-z0-9\+\-\.]+)/",
        "svn://svn.debian.org/s?v?n?/?debichem/experimental/([a-z0-9\+\-\.]+)/",
        "svn://svn.debian.org/s?v?n?/?debichem/wnpp/([a-z0-9\+\-\.]+)/",
        # Debian Science
        "svn://svn.debian.org/s?v?n?/?debian-science/packages/R/([a-z0-9\+\-\.]+)/",
        "svn://svn.debian.org/s?v?n?/?debian-science/packages/([a-z0-9\+\-\.]+)/",
        # Other repositories
        "svn://svn.debian.org/.*/([a-z0-9\+\-\.]+)/trunk",
        "git://git.debian.org/.+/([a-z0-9\+\-\.]+).git",
        "git://anonscm.debian.org/.+/([a-z0-9\+\-\.]+).git",
        "://github.com/[A-Za-z0-9\+\-\.]+/([a-z0-9\+\-\.]+).git"
	) {
        return $1 if $self->url =~ m/$guess/;
    }
    return undef;
}

1;
