#! /bin/bash
# Last edited on 2024-08-05 15:00:13 by stolfi

# Argument {fp} must be a file in the current folder or some subfolder.
# Moves the file {fp} to "00-DOCS/" and leaves a link in its place.
# Creates the necessary links along the way.

fp="$1"; shift

# Make sure the path begins with "./":
if [[ "@${fp%%/*}" != "@." ]]; then fp="./${fp}"; fi

if [[ ( ! ( -d "${fp}" ) ) && ( ! ( -L "${fp}" ) ) ]]; then
  # Split into folder and item:
  dir="${fp%/*}"
  nam="${fp##*/}"
  echo "dir = ${dir} nam = ${nam}" 1>&2
  if [[ ( "@${dir}" == "@${fp}" ) || ( "@${nam}" == "@${fp}" ) ]]; then
    echo "** bug" 1>&2; exit 1
  fi
  chdir="${dir}"
  while [[ "/${chdir}" != "/." ]]; do
    echo "  chdir = ${chdir}" 1>&2
    ( cd ${chdir} && if [[ ! ( -L 00-DOCS ) ]]; then ln -v -s ../00-DOCS ; fi )
    ( cd ${chdir} && if [[ ! ( -L 00-REFS ) ]]; then ln -v -s ../00-REFS ; fi )
    chdir="${chdir%/*}"
  done
  ( cd ${dir} && mv ${nam} 00-DOCS/ && ln -v -s 00-DOCS/${nam} ) 
else
  echo "!! ${fp} is not a plain file, skipped" 1>&2
fi
