#!/bin/sh

TABLE=experiment

CURRENT_DIR=`pwd`
MY_DIR=`dirname $0` && cd $MY_DIR && MY_DIR=`pwd`
cd $CURRENT_DIR

POPULATE_SCRIPT=populate_$TABLE.sql
EXPERIMENT_STATION_FILE=$MY_DIR/experiment_station.txt

cp $POPULATE_SCRIPT $POPULATE_SCRIPT.new
experimentList=`cat $POPULATE_SCRIPT | grep INSERT | awk '{print $13}'`

# correct insert statements
cmd="cat $POPULATE_SCRIPT.new | sed \"s?name,?name, experiment_station_id, ?g\"     > $POPULATE_SCRIPT.new.2 && mv $POPULATE_SCRIPT.new.2 $POPULATE_SCRIPT.new"
eval $cmd || exit 1

# insert station id for each experiment
for e in $experimentList; do
    eName=`echo $e | sed "s?'??g" | sed "s?,??g"`
    echo "Working on experiment $eName"
    echo "Executing: cat $EXPERIMENT_STATION_FILE | grep $eName | head -1 | cut -f2 -d','"
    stationId=`cat $EXPERIMENT_STATION_FILE | grep $eName | head -1 | cut -f2 -d','`
    if [ -z "$stationId" ]; then
        stationId=1 # test station id
    fi
    echo "Mapped $eName => $stationId"
    cmd="cat $POPULATE_SCRIPT.new | sed \"s?$e?$e $stationId,?g\" > $POPULATE_SCRIPT.new.2 && mv $POPULATE_SCRIPT.new.2 $POPULATE_SCRIPT.new"
    eval $cmd || exit 1
done

