#!/bin/sh

cd `dirname $0`/..
if ! . ./s4-funcs.sh; then
  echo "Cannot find s4-funcs.sh, which should be located in $mydir/.."
  exit 1
fi

cnt0=`query "SELECT count(sql) FROM sqlite_master WHERE name='tblaccesses';"`
cnt1=`query "SELECT count(sql) FROM sqlite_master WHERE name='tblaccesses' AND sql LIKE '%cascade%';"`

if [ x"$cnt0" = x"1" -a x"$cnt1" = x"0" ]; then
  echo -n Start fixing accesslog table...
  query <<-EOF && echo ..Done
	BEGIN;
	CREATE TABLE "tblaccesses2" (user, tbl, tblrowid, time, primary key (user, tbl, tblrowid, time), FOREIGN KEY(user) REFERENCES user(name) ON DELETE CASCADE ON UPDATE CASCADE);
	INSERT INTO tblaccesses2 SELECT * FROM tblaccesses;
	DROP TABLE tblaccesses;
	ALTER TABLE tblaccesses2 RENAME TO tblaccesses;
	COMMIT;
	EOF
else
  echo No need to fix db.
fi
