#!/bin/sh

while getopts r i; do
  case $i in
    r)  mode=restore ;;
  esac
done
shift $((OPTIND - 1))

if [ -z "$2" ]; then
  cat<<-EOF >&2
	Usage:
	   $0 DB out.csv user(s)	- dump users to out.csv
	   $0 -r DB out.csv		- import nonexistent user from out.csv
	EOF
  exit 1
fi
   
target=$(cd `dirname "$1"`; pwd)/`basename $1`

db=$1
shift
out=$1
shift

if [ x"$mode" = x"restore" ]; then
  echo "begin;"
  echo ".read $out"
  echo "end;"
else
  echo ".output $out"
  for u; do
    echo ".mode insert user"
    echo "SELECT * FROM user   WHERE name LIKE '$u';"
    echo ".mode insert user_s"
    echo "SELECT * FROM user_s WHERE name LIKE '$u';"
    echo ".mode insert user_m"
    echo "SELECT * FROM user_m WHERE name LIKE '$u';"
  done
fi |  sqlite3 $db
