#!/bin/bash

# obfus: A SIMPLE BASH SCRIPT TO "OBFUSCATE" A JAVASCRIPT PROGRAM
# 
#      By Jeffrey S. Rosenthal (probability.ca), April 2022.
# 
# USAGE: obfus FILENAME
# 
# OPTIONAL: A file FILENAME.vars in the same directory, listing variables
#   to re-name.  (Punctuation and extra white space and digits are ignored.)
# 
# OUTPUT: A file FILENAME.obfus which is the obfuscated version,
#   i.e. a version which runs the same but cannot easily be read.
# 
# HOPEFULLY: The output file will run exactly like the original JavaScript.
# 
# WARNING: Do not include names in FILENAME.vars which appear within your
#          JavaScript program's string constants, or they will be modified.

set -e

# REMOVE COMMENTS AND CONVERT INPUT PROGRAM INTO ONE SIMPLE LONG LINE:
rm -f "$1.obfus$$"
cat "$1" \
	| sed 's/\/\/.*$//' \
	| tr '\t' ' ' \
	| tr '\n' ' ' \
	| sed 's/\/\*.*\*\///g' \
	| sed 's/  */ /g' \
	> "$1.obfus$$"

if test -f "$1.vars"
then
  # CLEAN UP THE "$1.vars" FILE INTO A SIMPLE FILE WITH ONE NAME PER LINE:
  rm -f "$1.varlist$$"
  cat "$1.vars" \
	| sed 's/\/\/.*$//' \
        | sed '/\"/d' \
  	| sed 's/\t/ /g' \
	| tr '\n' ' ' \
	| sed 's/\/\*.*\*\///g' \
	| sed "s/[^a-zA-Z0-9]/ /g" \
        | sed 's/ [0-9]*/ /g' \
	| sed 's/  */ /g' \
	| tr ' ' '\n' \
	| sed 's/^ //g' \
        | sed '/^$/d' \
        | sed '/^var$/d' \
        | sed '/^int$/d' \
        | sed '/^double$/d' \
        | sed '/^void$/d' \
        | sed '/^function$/d' \
	> "$1.varlist$$"

  # CHECK IF THE $RANDOM BUILT-IN FUNCTION IS INSTALLED:
  if [ ${RANDOM-} ]
  then
    makerandom=true
  else
    makerandom=false
  fi

  # REPLACE THE NAMES FROM varlist WITH MEANINGLESS NAMES:
  minvarlength=4   # Shorter variable names will not be changed.
  linenum=0
  cat "$1.varlist$$" \
	| while read theline
	do
	  linenum=$((linenum+1))
	  if (( ${#theline} >= $minvarlength ))
	  then
            if [ $makerandom = true ]
	    then
	      varname=a$((RANDOM+23456))$((linenum*7+953))$((RANDOM+34567))
	    else
	      varname=a$((linenum*8+4953))
	    fi
	    sed -i "s/$theline\([^a-zA-Z0-9]\)/$varname \1/g" "$1.obfus$$"
	  fi
	  
        done
fi

# COPY THE RESULT TO $1.obfus WITH EXTRA SPACING:
rm -f "$1.obfus"
(echo -n '          ' ; cat "$1.obfus$$" ; echo '') > "$1.obfus"
chmod 644 "$1.obfus"

# REMOVE THE TEMPORARY FILE(S).
rm -f "$1.obfus$$" "$1.varlist$$"

# OPTIONALLY, OUTPUT THE RESULT TO THE SCREEN, TOO:
#cat "$1.obfus"

