#!/bin/bash 
if [ -d ".megatest" ]
then
  echo ".megatest directory present."
  echo "You have already migerated. "
  exit
fi

mkdir -p .megatest
cp megatest.db .megatest/main.db
sqlite3 .megatest/main.db << END_SQL
delete from tests; 
delete from test_steps;
END_SQL
version_id=$(sqlite3 .megatest/main.db "select id from metadat where var = 'MEGATEST_VERSION'")
current_version=$(megatest -version)
sqlite3 .megatest/main.db "replace into metadat (id,var,val) values($version_id,'MEGATEST_VERSION','$current_version')"


sqlite3 megatest.db 'select id from runs' > runs.txt
for run in $(cat runs.txt)
do
   echo "working on run id $run"
   dbnum=$(($run%100))
   if [ ! -f ".megatest/$dbnum.db" ]
   then
     dbnum=$(($run%100))
     cp megatest.db .megatest/$dbnum.db
     sqlite3 .megatest/$dbnum.db  << END_SQL
     delete from tests where run_id in (select id from runs where id%100!=$dbnum); 
     delete from test_data; 
     delete from test_meta; 
     delete from test_rundat;
     delete from test_steps where not exists ( select id from tests where tests.id = test_steps.test_id);
     replace into metadat (id,var,val) values($version_id,'MEGATEST_VERSION','$current_version');
     VACUUM;
END_SQL
    	
    fi
done

