#!/bin/sh

RESIN_HOME=

usage() {
  echo "usage: install.sh [flags]"
  echo "flags:"
  echo "  -help                    : this usage message"
  echo "  -nsapi <nsapipath>       : path to nsapi conf"
  echo "  -resin_home <resin_home> : resin home"
}

while test "$#" -ne 0; do
    case "$1" in

    # Documented arguments
    -h | -help)       SHOW_HELP=true; shift;;
    -nsapi) CONF="$2"; shift 2;;
    -resin_home) RESIN_HOME="$2"; shift 2;;

    *)   shift ; break;
    esac
done

if test ! -r "$CONF"; then
    echo "Can''t find obj.conf in ${CONF}"
    exit 1
fi

CAUCHO_NSAPI=$RESIN_HOME/src/c/plugin/nsapi/caucho_nsapi.so
if test ! -r "$CAUCHO_NSAPI"; then
    echo "Can''t find caucho_nsapi.so in ${RESIN_HOME}"
    exit 1
fi

echo "Using Netscape installation in ${CONF}"

grep caucho_nsapi $CONF >/dev/null 2>/dev/null
if test "$?" -ne 0; then
  cp $CONF $CONF.bakorig
  
  cat > /tmp/cauchoawk$$ <<EOF
/^Init/ { print \$0; if (init == 0) { init = 1; }; next; }
       { if (init == 1) {
            init = 2;
            print "# load resin shared library";
            printf "Init fn=\"load-modules\" shlib=\"$CAUCHO_NSAPI\"";
	    print " funcs=\"caucho_service,caucho_filter,caucho_status\"";
         }
       }
/<Object name=default>/ { indefault=1; }
/<\/Object>/ {indefault=0;}
/NameTrans/ { if (indefault == 1 && filter == 0) {
		filter = 1;
                print "# you can change the conf value";
		print "NameTrans fn=\"caucho_filter\" conf=\"$RESIN_HOME/conf/resin.conf\" name=\"resin\"";
                print "# comment out the following in production sites";
		print "NameTrans fn=\"assign-name\" from=\"/caucho-status\" name=\"caucho-status\"";
	      }
            }
            { print \$0; }
END         {
              print "<Object name=\"resin\">";
              print "Service fn=\"caucho_service\"";
              print "</Object>";
              print "<Object name=\"caucho-status\">";
              print "Service fn=\"caucho_status\"";
              print "</Object>";
	    }
EOF
    awk -f /tmp/cauchoawk$$ $CONF > /tmp/cauchoout$$
    cp /tmp/cauchoout$$ $CONF
    rm /tmp/cauchoawk$$ /tmp/cauchoout$$
fi
