A stochastic model of optimal debt management and bankruptcy