#!/bin/bash

# --------------------------------------------------------------------------- #
# EF_JS_escape
# =============
# Perform JS escaping from pipe and command line.
#
# Arguments:
# -i ARG | --input ARG   Input to escape
# -i=ARG | --input=ARG
#          -             Read input from pipe
#          --            Stop command line parsing
#
# Escaping table
# Source: https://owasp.github.io/owasp-java-encoder/encoder/apidocs/org/owasp/encoder/Encode.html#forJavaScript(java.lang.String)
#
# ef_js_escape
# Input                     Output
# "                         \x22
# &                         \x26
# '                         \x27
# /                         \/
# \                         \\
# U+0000 to U+001F (\x##)   removed
#
# --------------------------------------------------------------------------- #

__ef_js_escape_function() {
    local _sed_cmd=''

    _sed_cmd='s/\\/\\\\/g'
    _sed_cmd="$_sed_cmd;s/\"/\\\x22/g"
    _sed_cmd="$_sed_cmd;s/'/\\\x27/g"
    _sed_cmd="$_sed_cmd;s/&/\\\x26/g"
    _sed_cmd="$_sed_cmd;s/\//\\\\\//g"

    tr -d $'\x00'$'\x01'-$'\x1F' | sed -e "${_sed_cmd}"

    # how to test -> printf "abc\nDde\tf" | tr -d $'\x09'$'\x0A' | od -bc
}

ef_js_escape() {
    local  _input=''
    local _pipe=false

    while [ "$#" -gt 0 ]; do
        case "$1" in
            -i|--input)
                _input="$2"
                shift
                ;;
            -i=*|--input=*)
                _input="${1#*=}"
                ;;
            -)
                _pipe=true
                ;;
            --)
                shift
                break
                ;;
            *)
                break
                ;;
        esac
        shift
    done

    if [ "${_pipe}" = true ]; then
        __ef_js_escape_function
    fi

    if [ -n "${_input}" ]; then
        # __ef_js_escape_function <<< "${_input}"
        # echo  "${_input}" | __ef_js_escape_function 
        printf "%s" "${_input}" | __ef_js_escape_function 
    fi

    return 0
}
