#!/bin/sh

if [ -z "$1" ]; then
  cat<<-EOF >&2
	Usage: ./add-user-csv.sh CSVfile >&2
	Csv file should be the form of:
	   username(email),notify-email,gecos,IniPassword
	Set $DISABLED for setting disabled password
	EOF
  exit 1
fi
   
target=$(cd `dirname "$1"`; pwd)/`basename $1`
encp=${DISABLED:+DisabledPassword}

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

sq $db<<-EOF |
	.mode csv
	CREATE TEMPORARY TABLE _newuser(user,email,gecos,inipswd);
	.import $target _newuser
	.mode list
	.sepa ,
	SELECT * FROM _newuser n
	WHERE NOT EXISTS (SELECT * FROM user WHERE name=n.user);
	EOF
while IFS=, read user email gecos inipswd
do
  encpswd=${encp:-`mycrypt "$inipswd" 'StOpmE'`}
  case "$user" in
    *\'*)	echo "Skipping [$user]"
		continue ;;
    *@*)	;;		# OK
    *)		echo "Skipping [$user] because of lacking email pattern" >&2
		continue ;;
  esac
  # echo "$user" "$user" "$inipswd" "$encpswd"
  query "INSERT INTO user VALUES('$user');" &&
    echo Adding $user
  dbsetbyid user "$user" email "$email"
  dbsetbyid user "$user" gecos "$gecos"
  dbsetbyid user "$user" pswd "$encpswd"
done
