#!/bin/sh

if [ -z "$1" ]; then
  cat<<-EOF >&2
	Usage: $0 CSVfile
	       DB=db/world.sq3 $0 CSVfile		# for other world
	Csv file should be the form of:
	   GroupName,UserName(email)
	or
	   GroupName,UserName(email),admin
	EOF
  exit 1
fi
cd `dirname $0`/..
if ! . ./s4-funcs.sh; then
  echo "Cannot find s4-funcs.sh, which should be located in $mydir/.."
  exit 1
fi

target=$(cd `dirname "$1"`; pwd)/`basename $1`

echo target=$target
echo DB=$DB
echo -n 'Proceed? (Ctrl-C to break)'
read x

query<<-EOF
	.mode csv
	CREATE TEMPORARY TABLE _gusers(gname, user, admin);
	.import $target _gusers
	REPLACE INTO grp SELECT distinct gname FROM _gusers;

	CREATE TEMPORARY TABLE _default_grp_attr(key, val);
	INSERT INTO _default_grp_attr
	VALUES ('tag', 'lecture'), ('mtime', datetime('now', 'localtime'));

	REPLACE INTO grp_s
	 SELECT gname, key, 'string', val, NULL
	 FROM (SELECT distinct gname FROM _gusers)
	      JOIN _default_grp_attr;
	REPLACE INTO grp_mem SELECT gname, user FROM _gusers;
	REPLACE INTO grp_adm SELECT gname, user
	FROM _gusers WHERE admin LIKE 'admin';
EOF
