#!/bin/sh

if [ -z "$S4MASTERDB" -o ! -s "$S4MASTERDB" ]; then
  return
fi
if [ "$db" -ef "$S4MASTERDB" ]; then
  return		# Points to the same file
fi

skey="skey-`basename $mydir`"
syncflag=$dbdir/usersynced
userupdateflag=`dirname $S4MASTERDB`/`basename $userupdateflag`
test ! -e "$userupdateflag"		&& return
test "$syncflag" -nt "$userupdateflag"	&& return
    
#  for sub.sq3
# 
#  main: user: 'taro', 'hanako', 'shige'
#  sub:  user: 'taro', 'hanako', 'shige'
#  sub2: user_s: ('taro', 't'), ('hanako', 'h'), ('shige', 's')
#  then update
# 

judgeequal() {
  read num
  test $num -eq 0 && touch $syncflag
  return $num
}

## sqlite3 -cmd '.timer 1' -cmd '.echo 1' $db <<EOF
err "Starting account synchronization"
err "db=$db mas=$S4MASTERDB sess=$sessdb"
sqlite3 -bail -cmd 'PRAGMA FOREIGN_KEYS=on' $db <<EOF | judgeequal
ATTACH DATABASE "$S4MASTERDB" AS m;
CREATE TABLE IF NOT EXISTS user(name, primary key(name));
BEGIN;
DElETE FROM main.user WHERE rowid NOT IN (SELECT rowid FROM m.user);
INSERT INTO main.user(rowid, name)
       SELECT rowid, name FROM m.user
       WHERE m.user.rowid NOT IN (SELECT rowid FROM user);
UPDATE user SET name = (SELECT name FROM m.user WHERE main.user.rowid=m.user.rowid);
DELETE FROM main.user_s;
INSERT INTO main.user_s(rowid, name, key, type, val, bin)
	SELECT rowid,* FROM m.user_s;
DELETE FROM main.user_m;
INSERT INTO main.user_m(rowid, name, key, type, val, bin)
	SELECT rowid,* FROM m.user_m
	WHERE key NOT LIKE '%cache%';
END;

/* Compare user tables */
WITH master AS (
  SELECT p.rowid,* FROM m.user p
  	 NATURAL LEFT JOIN m.user_s
	 NATURAL LEFT JOIN m.user_m
), annex AS (
  SELECT p.rowid,* FROM user p
  	 NATURAL LEFT JOIN user_s
 	 NATURAL LEFT JOIN user_m
), m_a AS (
  SELECT * FROM master EXCEPT SELECT * FROM annex
), a_m AS (
  SELECT * FROM annex EXCEPT SELECT * FROM master
) SELECT (SELECT count(*) FROM m_a) + (SELECT count(*) FROM a_m);

-- SELECT * FROM annex;
-- SELECT rowid,* FROM m.user LIMIT 10;
-- SELECT rowid,* FROM user WHERE rowid NOT IN (SELECT rowid FROM m.user);
DETACH DATABASE m;
EOF
err Done
