How to keep door open or closed automatically?
For an "off the shelf" solution, just use a door closer that has a "keep open" or "hold open" function. It will close the door, unless it's fully opened to the point of engaging the "keep open" function (or in some cases a knob on the close arm needs to be engaged to "keep open".) 

It will not do any "open if here, close if there" games. It might be possible to configure one to keep the door open unless latched closed, but I haven not ever seen/tried that, while the stock "keep closed" function is utterly standard.

Spring hinges (more common for home "door closer" function) and a doorstop with strong magnets for the "keep open" would be a less obtrusive method.