#! /bin/sh

# symtohd -- convert symlinks to hard links
# $Id: symtohd,v 1.3 1998/07/10 19:16:22 cdua Exp cdua $
# Carlos Duarte, 970607/980709

#trap -- 'rm -f /tmp/xpto' EXIT SIGINT

USAGE="\
usage: $0 [-hn] files...

  -h      this help
  -n      no op
  -v      be verbose

Produce output to feed shell, that converts symbolic links to hard links.
Files which arent symlinks are ignored.
"

while : ; do
	case x"$1" in 
	x-h)	echo "$USAGE"; exit 1 ;;
	x-n)	cmd=cat ;;
	x-v)	verb=1 ;;
	x--)	shift; break ;;
	x-?)	echo "invalid option -- `echo $1|cut -c2-`"
		echo "$USAGE"; exit 1 ;;
	*)	break ;;
	esac
	shift
done

# if _must_ accept on extra argument after options
if test $# -eq 0; then echo "$USAGE"; exit 1; fi

ls -ld $* | awk '
function dirname(s, p,p0) {
  p0 = 0
  for (;;) {
    p = index(substr(s,p0+1),"/")
    if (p == 0) break
    p0 += p
  }
  if (p0 == 0) return "."
  if (p0 == 1) return "/"
  return substr(s,1,p0-1)
}
! /^l/ { next }
{
  from=$NF
  to=$(NF-2)
  if (substr(from,1,1)!="/") {
    dir = dirname(to)
    if (dir != ".") from = dir "/" from
  }
  cmd=sprintf("rm -f %s && ln %s %s", to, from, to)
  if ('${verb-0}') printf "echo %c%s%c\n", 39,cmd,39 # 39: single quote
  print cmd
}' | ${cmd-sh}

#exit 0
exit
