#!/bin/sh

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

# Now Another world is ACTIVE
# sessdb=`dirname $S4MASTERDB`/sess.sq3
## skey="skey-`basename $mydir`"
syncflag=${db%.*}.synctime
userupdateflag=`dirname $S4MASTERDB`/`basename $userupdateflag`
err SYNCFLAG=$syncflag
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
# 

## sqlite3 -cmd '.timer 1' -cmd '.echo 1' $db <<EOF
err "Starting account synchronization"
err "db=$db mas=$S4MASTERDB sessdb=$sessdb"
# num=$(sqlite3 -bail -cmd 'PRAGMA FOREIGN_KEYS=on' $db <<EOF
cat > tmp/sql <<EOF
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 WHERE rowid NOT IN (SELECT rowid FROM m.user_s);
REPLACE INTO main.user_s(rowid, name, key, type, val, bin)
	SELECT rowid,* FROM m.user_s;
DELETE FROM main.user_m WHERE rowid NOT IN (SELECT rowid FROM m.user_m);
REPLACE 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
), thisworld 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 thisworld
), a_m AS (
  SELECT * FROM thisworld EXCEPT SELECT * FROM master
) SELECT (SELECT count(*) FROM m_a) + (SELECT count(*) FROM a_m);

-- SELECT * FROM thisworld;
-- SELECT rowid,* FROM m.user LIMIT 10;
-- SELECT rowid,* FROM user WHERE rowid NOT IN (SELECT rowid FROM m.user);
DETACH DATABASE m;
EOF
num=$(sqlite3 -bail -cmd 'PRAGMA FOREIGN_KEYS=on' $db < tmp/sql )
if [ $num -eq 0 ]; then
  touch $syncflag
fi
return $num
