#!/bin/sh -ef
# Link a forked package's files to the other repository

## SYNOPSIS:
## .Nm
## .Op Fl p Ar package
## .Op Ar file...

## DESCRIPTION:
## .Nm
## symlinks files to the current package directory from a separate instance of
## the same package. If the
## .Fl p
## flag and a
## .Ar package
## is specified,
## .Nm
## will link files from the given package instead.
##
## .Nm
## creates symbolic links of package files using the realpath of the file, so it
## is therefore not suitable for using within a git repository, and should only
## be used internally.
## see: cpt-fork.1

usage() {
    printf 'usage: %s [-p package] [file...]\n' "${0##*/}"
    exit 0
}

case "$1" in
    -p) pkg=$2; shift 2 ;;
    -h|--help|'') usage ;;
esac

oPKG="$(cpt-search -sd "${pkg:--o}")"

for file; do
    [ -e "${oPKG:?}/$file" ]
    [ -d "$file" ] && rm -rf "$file"
    ln -sf "$oPKG/$file" "$file"
    printf 'linked %s to %s\n' "$oPKG/$file" "$PWD/$file"
done