#!/usr/bin/env zsh
#
# zdir2org - output an org compatible structure representing filesystem
# from the point passed on the command line (or . by default)
#
# options:
#     none
#
# usage:
#     dir2org.zsh [DIR]...
#
# ---
# author: Phil Jackson (phil@shellarchive.co.uk)

set -e

headline() {
  depth="${1}"
  text="${2}"

  printf "%${depth}s %s" "" | tr ' ' '*'
  echo " ${text}"
}

scan_and_populate() {
  depth="${1}"
  dir="${2}"

  headline "${depth}" "${dir}"

  # if there is no files in dir then just move on
  [ "$(ls "${dir}" | wc -l)" -eq 0 ] && return

  ((depth += 1))

  for f in $(ls -d "${dir}"/*); do
    if [ -d "${f}" ]; then
      scan_and_populate "${depth}" "${f}"
    else
      headline "${depth}" "[[file://${f}][${${f##*/}%.*}]]"
    fi
  done

  ((depth -= 1))
}

main() {
  scan_dir="${1:-$(pwd)}"
  depth=0

  scan_and_populate "${depth}" "${scan_dir}"
}

main "${@}"
