#!/bin/sh

CPOLD="./cp-8.21"
CPNEW="./cp-new "

{
  echo "Prepare tests ..."
  set -x
  mkdir d d/d2
  touch f
  touch d/f2
  touch d/d2/f3

  ln -s d dirlink
  ln -s f filelink
  ln -s nowhere danglink
  ln -s f2 d/fl
  ln -s d2 d/dl
  find f* d* -exec ls -ldogi '{}' +
  set +x

  echo "Starting tests ..."
  
  for src in filelink dirlink danglink ; do
    # target
    tgt=$(readlink $src)
    # src and tgt inodes
    ino_src="$(stat -c '%i' $src 2>/dev/null)"
    ino_tgt="$(stat -c '%i' $tgt 2>/dev/null)"
    # src and tgt file type
    typ_src="$(stat -c '%F' $src 2>/dev/null)"
    typ_tgt="$(stat -c '%F' $tgt 2>/dev/null)"
    
    for deref in '' -P -L -H ; do
      for l in '' -l -s ; do
        for r in '' -R ; do
          for p in '' --preserve=links ; do
          echo
          echo "========================================"
          echo "Test: cp $deref $l $r $p $src ..."
          set -x
          $CPOLD $deref $l $r $p $src OLD; rc_old=$?
          $CPNEW $deref $l $r $p $src NEW; rc_new=$?
          set +x

          # Does the destination exist?
          [ -e OLD ]; exist_old=$?
          [ -e NEW ]; exist_new=$?

          # Is the inode number identical to src and/or tgt?
          ino_old="$(stat -c '%i' OLD 2>/dev/null)"
          ino_new="$(stat -c '%i' NEW 2>/dev/null)"
          [ "$ino_old" = "$ino_src" ]; ino_old_src=$?
          [ "$ino_old" = "$ino_tgt" ]; ino_old_tgt=$?
          [ "$ino_new" = "$ino_src" ]; ino_new_src=$?
          [ "$ino_new" = "$ino_tgt" ]; ino_new_tgt=$?

          # What's the file type?          
          typ_old="$(stat -c '%F' OLD 2>/dev/null)"
          typ_new="$(stat -c '%F' NEW 2>/dev/null)"
          [ "$typ_old" = "$typ_src" ]; typ_old_src=$?
          [ "$typ_old" = "$typ_tgt" ]; typ_old_tgt=$?
          [ "$typ_new" = "$typ_src" ]; typ_new_src=$?
          [ "$typ_new" = "$typ_tgt" ]; typ_new_tgt=$?

          find $src $tgt OLD NEW \
            -exec ls -ldogi '{}' + 2>/dev/null \
            | sort -k1n

          if [ "$exist_old.$ino_old_src.$ino_old_tgt.$typ_old_src.$typ_old_tgt$rc_old" \
             = "$exist_new.$ino_new_src.$ino_new_tgt.$typ_new_src.$typ_new_tgt$rc_new" ]
          then
            echo "=== OK"
          else
            echo "=== DIFFERENCE in Test: cp $deref $l $r $p $src ..."
          fi
          
          rm -rf OLD NEW
          echo
          done
        done
      done
    done
  done

  echo
  echo "=== Cleanup"
  rm -rf d f filelink dirlink danglink
} 2>&1
