#!/bin/sh

if [ -z "$srcdir" ]; then
 srcdir=.
fi

pwsafe=$srcdir/pwsafe
file=/tmp/create_test.dat$$
err=/tmp/create_test.err$$
out=/tmp/create_test.out$$
pw=abcdefg

# create a new empty database
[ ! -f $file ] || rm $file
if [ -f $file ]; then
  echo "Can't clean up $file. Please delete it yourself and then rerun this test"
  exit 1
fi

echo -n "testing creation of new db $file: "
cmdline="$pwsafe -f $file --createdb"
$cmdline 2>$err 1>&2 <<EOF
$pw
$pw
EOF

if [ $? -ne 0 -o ! -r $file ]; then
  echo "FAILED!"
  echo "pwsafe is NOT WORKING PROPERLY. It is unable to create $file (passphase: $pw)."
  echo "Here is the cmdline:"
  echo "$cmdline"
  echo "Here is the output:"
  cat $err
  exit 1
else
  echo OK
fi

# read back new and supposedly empty database
echo -n "testing readback of new db $file: "
cmdline="$pwsafe -f $file --exportdb"
$cmdline 2>$err 1>$out <<EOF
$pw
EOF

RC=$?
grep <$out "# passwordsafe version 2.0 database" >/dev/null
RC="$RC$?"
grep <$out "^uuid	group	name	login	passwd	notes" >/dev/null
RC="$RC$?"

if [ $RC -ne 0 ]; then
  echo "FAILED!"
  echo "pwsafe is NOT WORKING PROPERLY. It is unable to read back $file (passphrase: $pw)."
  echo "Here is the cmdline:"
  echo "$cmdline"
  echo "Here is the output:"
  cat $err
  cat $out
  exit 1
else
  echo OK
fi

# add an entry to the new database
echo -n "testing adding of an entry to db $file: "
cmdline="$pwsafe -f $file --add test_group.test_name"
$cmdline 2>$err 1>&2 <<EOF
$pw
test_login
test_pw
test_pw
test_notes
EOF

if [ $? -ne 0 ]; then
  echo "FAILED!"
  echo "pwsafe is NOT WORKING PROPERLY. It is unable to add entry to $file (passphrase: $pw)."
  echo "Here is the cmdline:"
  echo "$cmdline"
  echo "Here is the output:"
  cat $err
  exit 1
else
  echo OK
fi

# read back new entry
echo -n "testing readback of db $file: "
cmdline="$pwsafe -f $file --exportdb"
$cmdline 2>$err 1>$out <<EOF
$pw
EOF

if [ $? -ne 0 ]; then
  echo "FAILED!"
  echo "pwsafe is NOT WORKING PROPERLY. It is unable to read back its new entry in $file (passphrase: $pw)."
  echo "Here is the cmdline:"
  echo "$cmdline"
  echo "Here is the output:"
  cat $out
  cat $err
  exit 1
fi

grep <$out "# passwordsafe version 2.0 database" >/dev/null
RC=$?
grep <$out "^uuid	group	name	login	passwd	notes" >/dev/null
RC="$RC$?"
grep <$out '^"........-....-....-....-............"	"test_group"	"test_name"	"test_login"	"test_pw"	"test_notes"' >/dev/null
RC="$RC$?"

if [ $RC -ne 0 ]; then
  echo "FAILED!"
  echo "pwsafe is NOT WORKING PROPERLY. Did not find expected output when reading back new entry in $file (passphrase: $pw)."
  echo "Here is the cmdline:"
  echo "$cmdline"
  echo "Here is the output:"
  cat $out
  cat $err
  exit 1
else
  echo OK
fi

# cleanup after ourselves
rm $file $file~ $err $out

exit 0

