That's why you rarely (never?) see a drug company take an old, off-patent drug and try and get a patent for it (in it's original form) on a new disease. Since there is no way to recoup any investment costs, they simply don't make the investment.
What does happen is that drug companies will take an old, off-patent drug and modify it somehow so that it can be patented. They can do that a number of different ways: create a unique formulation of the drug, create a drug-device combination product or try and create a slightly modified (and hopefully improved) version of the original drug.
Under the current system, unless you have a patent (or marketing exclusivity from the FDA) you have no opportunity to recoup any investment you made in the drug.
The doctor? He doesn't really make a profit of this and at least over here in Austria, a doctor may prescribe any substance he wants as long as he can argue that it is for the well-being of his patient.
The producer of the diabetes drugs? They don't sell it as a cancer drug.
The apothecary? He's just following the doctor's orders.