As the question seems to be twofold: a) check if run locally or via ssh and b) prevent to run twice, let me add a little bit about b) to Jakuje's answer how check for a).
PID and lock files are a quite common approach to this issue on Unix systems to ensure that a program runs only once. Usually those files are placed in
/var/lock/. First thing your script does is to check for the existence of these files. If they do that would mean that it's already running or has been exited disgracefully (aka crashed) - which is obviously the main drawback of this otherwise simple approach. If the files do not exist, your script writes it's PID and/or a lock file and normally proceeds to do whatever it is meant to do. Upon exit it should clean up PID and lock file.
See here for more advice.