fix username to be username instead of dbname and make file write atomic

Also this purges old entries