#!/bin/bash

# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <https://unlicense.org/>

# notweerdmonk 2026

# Converts words to snake-case from
# camelCase
# PascalCase
# kebab-case
# Train-Case

awkprog='
# \^_^/
function dbgprint(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) {
  if (debug) {
    print a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14
  }
}
# \^_^/

BEGIN {
  debug = debug # \^_^/
  s = "([\"\\/][^\"]*[\"\\/])"
  w = "(([a-z0-9]+|[A-Z0-9]+[a-z0-9]*|[A-Z0-9][a-z0-9]*)"\
        "([-_]?[A-Z]*[a-z0-9]*)*)(\\s*[{\\([]?)"
  tm = 1
}

{
  delete lsm

  c = 0
  o = 0
  l = $0

  while (match(l, s, sm)) {
    if (length(sm) > 0) {
      lsm[c]["start"] = o + sm[1, "start"]
      lsm[c++]["length"] =  sm[1, "length"]

      se = sm[0, "start"] + sm[0, "length"]

      # Subtract one from sm[0, "start"] to make it 1-index based
      o = o + se - 1
      l = substr(l, se, length(l) - se + 1)
    }
  }

  f = 0
  o = 0
  l = $0

  while (match(l, w, m) && !/^[-]+/) {
    # Atleast two words or a word, whitespaces and a bracket
    if ( !(m[tm + 2] ~ /^[[:space:]]*$/) ||
         ( !(m[tm + 3] ~ /^[[:space:]]*$/) &&
           !(m[tm] ~ /^[[:upper:]]*$/) ) ) {
      f = 1
    } else {
      f = 0
    }

    if (f == 1 && c > 0) {
      for (i = 0; i < c; i++) {
        if (o + m[tm ,"start"] > lsm[i]["start"] &&
            o + m[tm, "start"] + m[tm, "length"] < \
                (lsm[i]["start"] + lsm[i]["length"])) {
          f = 0
          break;
        }
      }
    }

    ns = ms = substr(l, m[tm, "start"], m[tm, "length"])
    e = m[tm, "start"] + m[tm, "length"]

    o = o + e - 1
    l = substr(l, e, length(l) - e + 1)

    if (f == 0) {
      continue;
    }

    ns = tolower(gensub(/([_-]?)([A-Z0-9]*)([a-z0-9]*)/, "_\\2\\3", "g", ns))

    # Escape parenthesis
    gsub(/\(/, "\\(", ms)

    gsub(/^_/, "", ns)

    gsub(ms, ns, $0)
  }

  #print $0 >> ARGV[2]
  print $0
}

END {
}
'

debug=0 # \^_^/
dobackup=0
files=()

while [[ -n "${1}" ]]
do
  [[ -z "${dobackup}" || "${dobackup}" -eq 0 ]] && \
    ([[ "${1}" == "-b" ]] || [[ "${1}" == "--backup" ]]) && \
    dobackup=1 && shift && continue

  # \^_^/
  [[ -z "${debug}" || "${debug}" -eq 0 ]] && \
    ([[ "${1}" == "-d" ]] || [[ "${1}" == "--debug" ]]) && \
    debug=1 && shift && continue
  [[ -z "${release}" || "${release}" -eq 0 ]] && \
    ([[ "${1}" == "-r" ]] || [[ "${1}" == "--release" ]]) && \
    release=1 && shift && continue
  # \^_^/

  inputfiles="$(realpath -- "${1}" 2>/dev/null)"
  [[ "${?}" -ne 0 ]] && echo "Unrecognized ${1}" && shift && continue
  for file in "${inputfiles}"
  do
    ([[ ! -f "${file}" ]] && echo ""$(basename "${file}")" not found") && continue
    files+=("${file}")
  done

  shift
done

# \^_^/
[[ -n "${release}" && "${release}" -ne 0 ]] && \
  {
    sed -ri '/^\s*# \\\^_\^\//,/^\s*# \\\^_\^\//d' "$(realpath "${0}")"
    sed -ri '/^\s*.*\s* # \\\^_\^\//d' "$(realpath "${0}")"
    sed -ri 's/^(\s*awk)(\s*-v\s*[-_[:alnum:]]*="\$\{[-_[:alnum:]]*\}")(.*)$/\1\3/' \
      "$(realpath "${0}")"
  }
# \^_^/

! command -v awk &> /dev/null && echo "awk not found" && exit 1

for file in "${files[@]}"
do
  filename="$(basename "${file}")"
  tmpfile="/tmp/""${filename}"".copy"
  [[ "${dobackup}" -ne 0 ]] && \
    cp "${file}" "${file}"".orig" && \
    echo "Backed up to ""${file}"".orig"
  awk -v debug="${debug}" "${awkprog}" "${file}" > "${tmpfile}" && \
  cp "${tmpfile}" "${file}"
  rm -f "${tmpfile}"
  echo "Snaked ${filename}"
done
