#!/bin/busybox sh

if [ $# -eq 0 ] ; then
  echo "Usage: ${0##*/} rootDir"
  exit 1
fi
if ! cd "$1" ; then
  echo "NoDir: $1"
  exit 1
fi
if [ ! -x bin/busybox -o -L bin/busybox ] ; then
  echo "No bin/busybox on $1"
  exit 1
fi
absPathBB="$(readlink -f bin/busybox)"

tmpd=`mktemp -d /tmp/busyboxRelink_XXXXXX`
appletList=$tmpd/aplstPath
curList=$tmpd/aplstCur
appletNameList=$tmpd/aplstName

./bin/busybox --list-full | sort > $appletList
dList="$(sed 's,/[^/]*$,,' $appletList | sort | uniq)"

get_cLink () {
  case "$1" in
  */*/*/*) echo "TooDeepDir: $1" 1>&2; return 1 ;;
  */*/*) cLink='../../bin/busybox' ;;
  bin/*) cLink='busybox' ;;
  */*)   cLink='../bin/busybox' ;;
  *)     cLink='bin/busybox' ;;
  esac
  return 0
}

linkCorrect () {
  [ "$(readlink -f "$1")" = "$absPathBB" ] || return 0
  get_cLink "$1" || return 0
  if [ "$(readlink "$1")" != $cLink ] ; then
    echo "LinkCorrection: $1" 1>&2
    ln -sf "$cLink" "$1"
  fi
  echo "$1"
}

# Current link correction and list
for d in $dList ; do
  if [ -d "$d" -a ! -L "$d" ] ; then
    for applet in "$d"/* ; do
      [ -L "$applet" ] || continue
      linkCorrect "$applet"
    done
  elif [ -L "$d" -a ! -d "$d" ] ; then
   linkCorrect "$d"
  fi
done > $curList

# Warn NonstandardPath and Delete NonApplet
./bin/busybox --list | sed 's#^#/#;s#$#/#' > $appletNameList
sort $appletList $appletList $curList | uniq -u | while read x ; do
  if grep -F -q "/${x##*/}/" $appletNameList ; then
    echo "NonstandardPath: $x ; #Keep" 1>&2
  else
    echo "NonApplet: $x ; #Delete" 1>&2
    rm -f "$x"
  fi 
done

# Make lost links
while read -r x ; do
  [ -e "$x" -o -L "$x" ] && continue
  if get_cLink "$x" ; then
    echo "NewLink: $x" 1>&2
    ln -s "$cLink" "$x"
  fi
done < $appletList

rm -rf "$tmpd"

exit

