How to “reset” a Mac OS X installation

Here’s how to “reset” an installed Mac OS X and virtually return to a “virgin” state with a welcome screen prompting the user to setup and customize his Mac OS X installation:

0. To reset a Mac OS X v10.7 Lion installation to factory default, check Mark’s comment @ Apple forum (basically, deleting users before booting into single user mode seems to do the trick). For Mac OS X v10.6 Snow Leopard and older, follow the procedure below.

1. Press Command-S during startup to get into single user mode
2. Check the filesystem:
# /sbin/fsck -fy
3. Mount the root partition as writable:
# /sbin/mount -uw /
4. Remove the hidden .AppleSetupDone file:
# rm /var/db/.AppleSetupDone
5. a) For Mac OS X 10.5 ‘Leopard’ and newer, do:
# launchctl load /System/Library/LaunchDaemons/com.apple.DirectoryServices.plist
Repeat for every user previously defined on the machine (replace {username} with the real user name):
# dscl . -delete /Users/{username}
# dscl . -delete /Groups/admin GroupMembership {username}

5. b) For older versions of Mac OS X, do:
# rm -rf /var/db/netinfo/local.nidb
6. Remove the home directories of users. For every user do (replace {username} with the real user name):
# rm -rf /Users/{username}
7. If applicable, remove already created files in root’s home directory, e.g.
# rm /root/.bash_history
8. Shutdown (or reboot to verify the procedure worked):
# shutdown -h now
-or-
# reboot

That’s it! :)

[Update 20081106]: Thanks to Macs R We for the update 5 a) regarding Mac OS X Leopard! See the comments below for more information.

[Update 20090429]: Added “dscl . -delete /Groups/admin GroupMembership {username}” to 5b) as suggested by rello (see rello’s comment below)

[Update 20110731]: Some updates about resetting Mac OS X v10.7 Lion (unverified) and a clarification that rebooting at the end isn’t strictly necessary (just to verify the procedure worked). Thanks to David, Adrien and Adam for the hints.