#!/bin/sh

if [ -z "$1" ]; then
  cat<<-EOF >&2
	Usage: ./remove-user-csv.sh CSVfile
	Csv file should be the form of:
	   username(email)
	EOF
  exit 1
fi
outdelim() echo "------------------------------------------------"

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

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

outdelim
query<<-EOF
	CREATE TEMPORARY TABLE _rmuser(user);
	.import $target _rmuser
	.mode list
	.head 1
	SELECT name,
	       max(CASE key WHEN 'gecos' THEN val END) gecos,
	       max(CASE key WHEN 'login' THEN val END) login
	FROM   user_s
	WHERE name IN (SELECT * FROM _rmuser)
	GROUP by name;
	SELECT count(name) || ' users' "To be removed"
	FROM user WHERE name IN (SELECT * FROM _rmuser);
	EOF

outdelim
echo "Remove them? (Type C-c to abort)" >&2
read ans

# Remove users in Base World
query "DELETE FROM user WHERE name IN (SELECT * FROM _rmuser);"

# Remove users in Extra World
for world in $S4WORLDLIST; do
  case "$world" in			# tag:shortname:desc
    *:*:*:*) continue ;;
    *:*:*)
      t_s=${world%:*}			# tag:shortname
      d=${world##*:}			# desc
      w=${t_s#*:}			# shortname
      ;;
    *) continue ;;
  esac
  wdb=`(unset DB; . ./s4-config-$w.sh; echo $DB)`
  echo "Operate on world $d($wdb)" >&2
  query <<-EOF
	ATTACH DATABASE "$wdb" AS w;
	DELETE FROM w.user WHERE name IN (SELECT * FROM _rmuser);
	DETACH DATABASE w;
	EOF
done
