When the petitioner is so sick or infirm that the petitioner would be endangered if brought before the judge before whom the writ is returnable, the person having the petitioner in custody may state that fact in the return. If the judge finds that the statement is true, and the return is otherwise sufficient, the judge shall decide upon the return and dispose of the matter in accordance with law. The petitioner under this section may appear by attorney and plead to the return as if present. If the petitioner is illegally imprisoned or restrained of liberty, the judge shall order those having custody to immediately discharge the petitioner. If the petitioner is legally imprisoned or restrained and is not entitled to be released on bail, the judge shall dismiss the proceedings.