#!/bin/bash 

mkdir -p .db
cp megatest.db .db/main.db
sqlite3 .db/main.db << END_SQL
delete from tests; 
delete from test_steps;
END_SQL
version_id=$(sqlite3 .db/main.db "select id from metadat where var = 'MEGATEST_VERSION'")
current_version=$(megatest -version)
sqlite3 .db/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
   dbnum=$(($run%100))
   cp megatest.db .db/$dbnum.db
   sqlite3 .db/$dbnum.db  << END_SQL
   delete from tests where run_id != $run; 
   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');
END_SQL
done

