Reconstructing the history of water ice formation from HDO/H2O and D2O/HDO ratios in protostellar cores