#!/bin/sh
# -*- perl -*-
# This code allows us to start perl from our path or an environment variable
# rather than hardcoding a path into the #! line.  It works from sh or csh.
(exit $?0) && eval 'exec ${QPERLQ-perl} -x $0 ${1+"$@"}'
if (! $?QPERLQ) setenv QPERLQ perl
exec $QPERLQ -x $0 $argv:q

#!/usr/local/bin/perl -w
#
# $Id: follow,v 1.6 1998/05/10 14:29:51 ejb Exp $
# $Source: /home/ejb/scripts/RCS/follow,v $
# $Author: ejb $
#
# Given one argument, check to make sure it is a symbolic link
# to a file or directory.  If it is a link to a directory,
# replace it with a directory and populate it with symbolic
# links to all files in the original directory.	 If it is a
# file, replace the link with a copy of the file it is linked
# to.
#


$whoami = ($0 =~ m,([^/]*)$,) ? $1 : $0;

&usage if (scalar(@ARGV) != 1);

$link = $ARGV[0];
$link =~ s,/$,,;
if ($link =~ m,^(.*)/([^/]*)$,)
{
    $linkbase = $2;
    $linkdir = $1;
}
else
{
    $linkbase = $link;
    $linkdir = ".";
}

chdir($linkdir) || die "$whoami: can't chdir to $linkdir: $!\n";
$link = $linkbase;

(-l $link) || die "$whoami: LINK must be a symbolic link.\n";

$linkpath = readlink($link);

if (-d $link)
{
    # If this is a relative link, we will want to prepend ../ to the path
    # for the new subdirectory.
    $newdir = ($linkpath =~ m,^/,) ? $linkpath : "../$linkpath";

    # Get the files in the directory.
    if (opendir(DIR, $linkpath))
    {
	# Skip "." and ".."
	@files = readdir(DIR);
	shift(@files);
	shift(@files);
	closedir(DIR);
    }
    
    # Remove the link and create a real directory
    unlink($link);
    mkdir($link, 0777);

    for (@files)
    {
	symlink("$newdir/$_", "$link/$_");
    }
}
elsif (-f $link)
{
    # Remove the link and copy the file
    unlink($link);
    system("cp -p $linkpath $link");
}
else
{
    die "$whoami: LINK must be a symbolic link to a file or directory.\n";
}

exit 0;

sub usage {
    print STDERR "Usage: $whoami LINK\n";
    print STDERR "  LINK is a symbolic link to a file or directory.\n";
    exit 1;
}
