#!/bin/sh
dst=${1}
project=${2}
scanner=${3}

entry_addr=${dst%.sh}
entry_addr=${entry_addr##*-}
project=${dst%/*}
project=${project##*/}
tmp=${TEVWH_TMP}/${project}/${entry_addr}

prefix="${TEVWH_PRE}/one_step_closer/test-prefix.sh"
postfix="${TEVWH_PRE}/one_step_closer/test-postfix.sh"

src="${TEVWH_OUT}/scanner/${scanner}/find-shell"
if [ -s "${src}" ]; then
  ${TEVWH_PATH_SED} \
  	-e "s|.*/\([^/]*\)$|#!${tmp}/\1_infected|" \
	-e 1q \
	"${src}" > "${dst}"
else
  echo "#!${TEVWH_PATH_SH}" > "${dst}"
fi

infect="${TEVWH_OUT}/scanner/${scanner}/infect"
[ -s "${infect}" ] || exit 1
first=$( ${TEVWH_PATH_SED} 1q "${infect}" )
[ -x "${first}" ] || exit 2

find_cmd()
{
  ${TEVWH_PATH_SED} -n -e "s#^\(${1}\>\)\(.*\)#${2}\1_infected\2#p" \
  < ./src/scanner/mkinfect.lst
}

first_cmd=$( find_cmd "${first##*/}" )

subst()
{
  ${TEVWH_PATH_SED} \
	-e "s#\${tmp}#${tmp}#g" \
	-e "s#\${first}#${first##*/}#g" \
	-e "s#\${first_cmd}#${first_cmd}#g"
}

subst < ${prefix} >> "${dst}"
${TEVWH_PATH_SED} -n -e 's#.*/\(.*\)#\1#' -e '2,$p' \
< ${infect} \
| while read program
do find_cmd ${program} ./
done >> "${dst}"
subst < ${postfix} >> "${dst}"
${TEVWH_PATH_CHMOD} 755 "${dst}"
