#!/bin/sh
#
# hm - Manage your config.h files on a per program basis.
# Store defaults and user configs, and restore them easily.
#
# ---
# source: https://git.z3bra.org/scripts/log.html

# Directory where configs are saved
basedir=~/.hm.d

# Default names for configs
default=config.def.h

# How to list files managed by hmgr
#listcmd='ls -1 --color=auto'
listcmd='tree -L 2 --noreport'

# Change output colors ?
color_conf='1;37' # colors for config files
color_dirs='0;33' # colors for directory names

usage() {
  echo "Usage: $(basename "$0") [-hu] [-l [dir]] [-di <file>] [-csr <dir>/<name>]"

  test -z "$1" && return

  cat <<EOF
    -h              : help
    -u              : shortcut for -n ${USER}.h

    -l [dir]        : list currently managed applications/files

    -d <dir>/<name> : remove <name> from managed configs
    -i <file>       : input file to use (defaults to ./config.h)

    -c <dir>        : check which config is in use
    -s <dir>/<name> : store \`config.h\` to <dir>/<name>
    -r <dir>/<name> : restore \`config.h\` from <dir>/<name>
EOF
}

store() {
  test -z "$1" && return 1

  # check if the user gave a filename or not
  # and deduct filepath from that
  if test "$(dirname "$1")" = '.'; then
    dir=$1
    filepath=${basedir}/${dir}/${default}
  else
    dir=$(dirname "$1")
    filepath=${basedir}/$1
  fi

  # create directory if it does not exist
  test ! -d "${basedir}/${dir}" && mkdir -p "${basedir}/${dir}"

  # Copy from current dir to base directory
  cp -i "${cin}" "${filepath}"
}

restore() {
  test -z "$1" && return 1

  if test -f "${basedir}/$1"; then
    filepath=${basedir}/$1
  else
    filepath=${basedir}/$1/${default}
  fi

  # Copy from base dir to current directory
  cp "${filepath}" "${cin}"
}

list() {
  # Go to the base directory
  cd "${basedir}" || exit 1

  "${listcmd}" "$1"
}

check() {
  found=0

  test ! -f "${cin}" && echo "cannot find file ${cin}" && exit 1

  for dir in "${basedir}"/*; do
    for file in "${dir}"/*; do
      if diff "${file}" "${cin}" >/dev/null 2>&1; then
        printf '%s' "${fgd}$(basename "${dir}")${nofg}/"
        printf '%s' "${fgh}$(basename "${file}")${nofg}\n"
        found=1
      fi
    done
  done
  test "${found}" -eq 0 && echo "${cin}" is different from stored configs
}

# No arguments? give usage
test $# -eq 0 && list && exit 0

# Create $basedir if it does not exists
test ! -d "${basedir}" && mkdir -p "${basedir}"

# Set the default file names
cin=config.h
list=0

# standardize colors for shell output
fgd="\e[${color_dirs}m"
fgh="\e[${color_conf}m"
nofg="\e[0m"

# change colors, for fun!
LS_COLORS="di=${color_dirs}:*.h=${color_conf}"
export LS_COLORS

# Parse options
while getopts "chi:ld:s:r:u" opt; do
  case ${opt} in
    # Check which config is in use
    c) check ;;

    # Wipe the config given as argument
    d) rm "${basedir}/${OPTARG}" ;;

    # Change the input file
    i) cin=${OPTARG} ;;

    # List currently managed config.h
    l)
      list=1
      break
      ;;

    # Whether to store or restore a config.h
    s) store "${OPTARG}" ;;
    r) restore "${OPTARG}" ;;

    # WHAAT?!
    h)
      usage full
      exit 0
      ;;
    *)
      usage
      exit 1
      ;;
  esac
done
# In case we want to list files managed...
shift "$((OPTIND - 1))"

# List either the whole dir or a specific one
test "${list}" -eq 1 && list "$1"
