#! /usr/bin/perl

# $OpenBSD: port-getpkgpath-helper,v 1.2 2023/05/30 05:34:08 espie Exp $
#
# Copyright (c) 2006 Marc Espie <espie@openbsd.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

use Cwd qw(abs_path);
use v5.36;

my $dir = shift;
my $path = $ENV{PORTSDIR_PATH} or exit 1;

my $pkgpath;
my $real_dir = abs_path($dir);
if (!defined $real_dir) {
	say STDERR "Error: $dir does not resolve (broken symlink ?)";
}
for my $d (split ':', $path) {
	my $real_d = abs_path($d);
	if (!defined $real_d) {
		say STDERR "Error: $d does not resolve (broken symlink ?)";
	}
	if ($real_dir =~ m/^\Q$real_d\E\//) {
		my $newpath = $';
		if (!defined $pkgpath or length $newpath < length $pkgpath) {
			$pkgpath = $newpath;
		}
	}
}
if (defined $pkgpath) { 
	say $pkgpath;
} else {
	print STDERR "Can't find $dir ";
	if ($real_dir ne $dir) {
		print STDERR "($real_dir) ";
	}
	say STDERR "under PORTSDIR_PATH=$path";
}
# XXX no error code because this is too verbose from the Makefile
exit 0;

