#!/bin/bash

item="${1}"
if [[ -z "${2}" ]]; then
  echo "must enter item and assignment"
  echo "$0 child.txt parent.txt"
  echo "$0 group@ parent@"
  exit 1
fi

itemgroup="false"
assigngroup="false"
thedir=$(pwd|awk -F'/' '{print $NF}');
if ( echo "${item}"|grep -q '@' ); then
  itemgroup="true"
  item="${item}*"
fi
for i in $(seq 2 ${#}); do
  if ( echo "${2}"|grep -q '@' ); then
    assigngroup="true"
    assign="${2}* ${assign}"
  else
    assign="${2} ${assign}"
  fi
  shift
done



ls ${item}|while read theitem; do
  addToBottom=$(grep '//keep' "${theitem}")
  sed -i '/addParent/d' ${theitem}
  if [[ "${assigngroup}" == "true" ]]; then
    sed -i '/^criteria/d' ${theitem}
    sed -i '/^setRequiresParents/d' ${theitem}
    echo 'setRequiresParents()' >> ${theitem}
  fi
  echo "${addToBottom}" >> "${theitem}"
  ls ${assign}|while read theassignment; do
    assignment=$(echo "${theassignment}"|sed 's/.txt//')
    echo "" >> ${theitem}
    echo 'addParent("triumph:'${thedir}'/'${assignment}'")' >> ${theitem}
  done
done

../organize "${item}"
