#! /bin/bash
# Last edited on 2024-12-31 07:16:51 by stolfi

# Moves git-managed test input file ${dir}/${sub}/${file} to ${dir}/${new}/${file} and
# leaves a relative symbolic link in its place.

dir="$1"; shift
new="$1"; shift
sub="$1"; shift
file="$1"; shift
if [[ ! ( -d ${dir}/${sub} ) ]]; then 
  echo "** ${dir}/${sub} does not exist or is not a directory" 1>&2 ; exit 1;
fi
if [[ ! ( -f ${dir}/${sub}/${file} ) ]]; then 
  echo "** ${dir}/${sub}/${file} does not exist or is not a plain file" 1>&2 ; exit 1;
fi

mkdir -p ${dir}/${new}
lkpref="../${new}"
ok=0
nt=0
cd ${dir}/${sub}
while [[ ( ${nt} -lt 10 ) && ( ${ok} -eq 0 ) ]]; do
  echo "trying ${lkpref}" 1>&2
  if [[ -d ${lkpref} ]]; then
    ok=1
  else
    lkpref="../${lkpref}"
    nt=$(( $nt + 1 ))
  fi
done
if [[ $ok -gt 0 ]]; then
  echo "git mv ${file} ${lkpref}/" 1>&2
  git mv ${file} ${lkpref}/
  ln -sv ${lkpref}/${file}
  git add --verbose ${file}
else
  echo "** can't get the relative link to ${new}" 1>&2; exit 1
fi
