A variational principle for the compaction of granular materials