#!/usr/bin/perl -w

use strict;

my $progname = "repolist";
my $version = "1.0";

# this hash table will be used to store package 'name version' pairs from the
# return of both pacman -Sl <repo> and pacman -Q output. We will then check
# to see if a value is in our table twice- if so, we will print that package
# as it is both in the repo we queried and installed on our local system.
my %packages = ();
my $output;
my $pkg;

if ($#ARGV != 0 || $ARGV[0] eq "--help" || $ARGV[0] eq "-h") {
	print "$progname - List all packages installed from a given repo\n";
	print "Usage:   $progname <repo>\n";
	print "Example: $progname testing\n";
	exit 0;
}

if ( $ARGV[0] eq "--version" || $ARGV[0] eq "-v") {
	print "$progname version $version\n";
	exit 0;
}


$output = `pacman -Sl $ARGV[0]`;
my @sync = split(/\n/, $output);
# sample output from pacman -Sl:
# testing foobar 1.0-1
foreach $pkg (@sync) {
       my @info = split(/ /, $pkg);
       # we only want to store 'foobar 1.0-1' in our hash table
       my $pkg = $info[1] . " " . $info[2];
       $packages{$pkg}++;
}

$output = `pacman -Q`;
# sample output from pacman -Q:
# foobar 1.0-1
my @local = split(/\n/, $output);
foreach $pkg (@local) {
       # store 'foobar 1.0-1' in our hash table
       $packages{$pkg}++;
}

# run comparison check- if value was added twice, it was in the intersection
my @intersection;
foreach my $element (keys %packages) {
       if ($packages{$element} == 2) {
               push @{ \@intersection }, $element;
       }
}

# print our intersection, and bask in the glory and speed of perl
@intersection = sort @intersection;
foreach $pkg (@intersection) {
       print $pkg . "\n";
}

