Set user environment variables permanently by using `--permanent` + deprecate `--global` (#621)

diff --git a/.circleci/config.yml b/.circleci/config.yml
index 8b39596..4a2b452 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -87,6 +87,16 @@
           command: |
             source emsdk_env.sh
             python scripts/test.py
+      - run:
+          name: --permanent test
+          shell: powershell.exe
+          command: |
+            try {
+              scripts/test_permanent.ps1
+            } catch {
+              Write-Host "`n Error Message: [$($_.Exception.Message)"] -ForegroundColor Red
+              Write-Host "`n Line Number: "$_.InvocationInfo.ScriptLineNumber -ForegroundColor Red
+            }
 
   build-docker-image:
     executor: bionic
diff --git a/README.md b/README.md
index 1e6fe00..829b93f 100644
--- a/README.md
+++ b/README.md
@@ -176,9 +176,8 @@
 
 You can toggle between different tools and SDK versions by running `emsdk
 activate <tool/sdk name>`. Activating a tool will set up `~/.emscripten` to
-point to that particular tool. On Windows, you can pass the option `--global` to
-the `activate` command to register the environment permanently to the system
-registry for all users.
+point to that particular tool. On Windows, you can pass the option `--permanent` to
+the `activate` command to register the environment permanently for the current user. Use `--system` to do this for all users.
 
 ### How do I build multiple projects with different SDK versions in parallel?
 
diff --git a/emsdk.py b/emsdk.py
old mode 100755
new mode 100644
index e4669ee..5e38497
--- a/emsdk.py
+++ b/emsdk.py
@@ -1760,18 +1760,13 @@
           return False
     return True
 
-  def win_activate_env_vars(self, permanently_activate):
+  def win_activate_env_vars(self, system):
     if WINDOWS:
       envs = self.activated_environment()
       for env in envs:
         key, value = parse_key_value(env)
 
-        if permanently_activate:
-          # If there is an env var for the LOCAL USER with same name, it will
-          # hide the system var, so must remove that first.
-          win_delete_environment_variable(key, False)
-
-        win_set_environment_variable(key, value, permanently_activate)
+        win_set_environment_variable(key, value, system)
 
   # If this tool can be installed on this system, this function returns True.
   # Otherwise, this function returns a string that describes the reason why this
@@ -2411,7 +2406,7 @@
 # Reconfigure .emscripten to choose the currently activated toolset, set PATH
 # and other environment variables.
 # Returns the full list of deduced tools that are now active.
-def set_active_tools(tools_to_activate, permanently_activate):
+def set_active_tools(tools_to_activate, permanently_activate, system):
   tools_to_activate = process_tool_list(tools_to_activate, log_errors=True)
 
   if tools_to_activate:
@@ -2433,13 +2428,13 @@
   if WINDOWS and permanently_activate:
     # Individual env. vars
     for tool in tools_to_activate:
-      tool.win_activate_env_vars(permanently_activate=True)
+      tool.win_activate_env_vars(system=system)
 
     # PATH variable
-    newpath, added_items = adjusted_path(tools_to_activate, system_path_only=True)
+    newpath, added_items = adjusted_path(tools_to_activate, system=system)
     # Are there any actual changes?
     if newpath != os.environ['PATH']:
-      win_set_environment_variable('PATH', newpath, system=True)
+      win_set_environment_variable('PATH', newpath, system=system)
 
   return tools_to_activate
 
@@ -2485,17 +2480,12 @@
 
 # Looks at the current PATH and adds and removes entries so that the PATH reflects
 # the set of given active tools.
-def adjusted_path(tools_to_activate, log_additions=False, system_path_only=False):
+def adjusted_path(tools_to_activate, system=False):
   # These directories should be added to PATH
   path_add = get_required_path(tools_to_activate)
   # These already exist.
   if WINDOWS and not MSYS:
-    existing_path = win_get_environment_variable('PATH', system=True)
-    if not system_path_only:
-      current_user_path = win_get_environment_variable('PATH', system=False)
-      if current_user_path:
-        existing_path += ENVPATH_SEPARATOR + current_user_path
-    existing_path = existing_path.split(ENVPATH_SEPARATOR)
+    existing_path = win_get_environment_variable('PATH', system=system).split(ENVPATH_SEPARATOR)
   else:
     existing_path = os.environ['PATH'].split(ENVPATH_SEPARATOR)
   emsdk_root_path = to_unix_path(emsdk_path())
@@ -2737,15 +2727,21 @@
 
     if WINDOWS:
       print('''
-   emsdk activate [--global] [--build=type] [--vs2017/--vs2019] <tool/sdk>
+   emsdk activate [--permanent] [--system] [--build=type] [--vs2017/--vs2019] <tool/sdk>
 
                                 - Activates the given tool or SDK in the
-                                  environment of the current shell. If the
-                                  --global option is passed, the registration
-                                  is done globally to all users in the system
-                                  environment.  If a custom compiler version was
-                                  used to override the compiler to use, pass
-                                  the same --vs2017/--vs2019 parameter
+                                  environment of the current shell.
+
+                                - If the `--permanent` option is passed, then the environment
+                                  variables are set permanently for the current user.
+
+                                - If the `--system` option is passed, the registration
+                                  is done for all users of the system.
+                                  This needs admin privileges
+                                  (uses Machine environment variables).
+
+                                - If a custom compiler version was used to override
+                                  the compiler to use, pass the same --vs2017/--vs2019 parameter
                                   here to choose which version to activate.
 
    emcmdprompt.bat              - Spawns a new command prompt window with the
@@ -2775,7 +2771,14 @@
 
   arg_old = extract_bool_arg('--old')
   arg_uses = extract_bool_arg('--uses')
+  arg_permanent = extract_bool_arg('--permanent')
   arg_global = extract_bool_arg('--global')
+  arg_system = extract_bool_arg('--system')
+  if arg_global:
+    print('--global is deprecated. Use `--system` to set the environment variables for all users')
+    arg_system = True
+  if arg_system:
+    arg_permanent = True
   if extract_bool_arg('--embedded'):
     errlog('embedded mode is now the only mode available')
   if extract_bool_arg('--no-embedded'):
@@ -2937,7 +2940,7 @@
     print('Items marked with * are activated for the current user.')
     if has_partially_active_tools[0]:
       env_cmd = 'emsdk_env.bat' if WINDOWS else 'source ./emsdk_env.sh'
-      print('Items marked with (*) are selected for use, but your current shell environment is not configured to use them. Type "' + env_cmd + '" to set up your current shell to use them' + (', or call "emsdk activate --global <name_of_sdk>" to permanently activate them.' if WINDOWS else '.'))
+      print('Items marked with (*) are selected for use, but your current shell environment is not configured to use them. Type "' + env_cmd + '" to set up your current shell to use them' + (', or call "emsdk activate --permanent <name_of_sdk>" to permanently activate them.' if WINDOWS else '.'))
     if not arg_old:
       print('')
       print("To access the historical archived versions, type 'emsdk list --old'")
@@ -2971,8 +2974,8 @@
     fetch_emscripten_tags()
     return 0
   elif cmd == 'activate':
-    if arg_global:
-      print('Registering active Emscripten environment globally for all users.')
+    if arg_permanent:
+      print('Registering active Emscripten environment permanently')
       print('')
 
     tools_to_activate = currently_active_tools()
@@ -2987,12 +2990,12 @@
     if not tools_to_activate:
       errlog('No tools/SDKs specified to activate! Usage:\n   emsdk activate tool/sdk1 [tool/sdk2] [...]')
       return 1
-    active_tools = set_active_tools(tools_to_activate, permanently_activate=arg_global)
+    active_tools = set_active_tools(tools_to_activate, permanently_activate=arg_permanent, system=arg_system)
     if not active_tools:
       errlog('No tools/SDKs found to activate! Usage:\n   emsdk activate tool/sdk1 [tool/sdk2] [...]')
       return 1
-    if WINDOWS and not arg_global:
-      errlog('The changes made to environment variables only apply to the currently running shell instance. Use the \'emsdk_env.bat\' to re-enter this environment later, or if you\'d like to permanently register this environment globally to all users in Windows Registry, rerun this command with the option --global.')
+    if WINDOWS and not arg_permanent:
+      errlog('The changes made to environment variables only apply to the currently running shell instance. Use the \'emsdk_env.bat\' to re-enter this environment later, or if you\'d like to permanently register this environment permanently, rerun this command with the option --permanent.')
     return 0
   elif cmd == 'install':
     # Process args
diff --git a/scripts/test_permanent.ps1 b/scripts/test_permanent.ps1
new file mode 100644
index 0000000..01ec1f1
--- /dev/null
+++ b/scripts/test_permanent.ps1
@@ -0,0 +1,56 @@
+$repo_root = [System.IO.Path]::GetDirectoryName((resolve-path "$PSScriptRoot"))
+
+& "$repo_root/emsdk.ps1" install latest
+& "$repo_root/emsdk.ps1" activate latest --permanent
+
+$EMSDK_USER = [System.Environment]::GetEnvironmentVariable("EMSDK", "User")
+$EM_CONFIG_USER = [System.Environment]::GetEnvironmentVariable("EM_CONFIG", "User")
+$EMSDK_NODE_USER = [System.Environment]::GetEnvironmentVariable("EMSDK_NODE", "User")
+$EMSDK_PYTHON_USER = [System.Environment]::GetEnvironmentVariable("EMSDK_PYTHON", "User")
+$JAVA_HOME_USER = [System.Environment]::GetEnvironmentVariable("JAVA_HOME", "User")
+$EM_CACHE_USER = [System.Environment]::GetEnvironmentVariable("EM_CACHE", "User")
+$PATH_USER = [System.Environment]::GetEnvironmentVariable("PATH", "User")
+
+if (!$EMSDK_USER) {
+    throw "EMSDK is not set for the user"
+}
+if (!$EM_CONFIG_USER) {
+    throw "EM_CONFIG_USER is not set for the user"
+}
+if (!$EMSDK_NODE_USER) {
+    throw "EMSDK_NODE is not set for the user"
+}
+if (!$JAVA_HOME_USER) {
+    throw "JAVA_HOME is not set for the user"
+}
+if (!$EMSDK_PYTHON_USER) {
+    throw "EMSDK_PYTHON is not set for the user"
+}
+if (!$EM_CACHE_USER) {
+    throw "EM_CACHE is not set for the user"
+}
+
+
+$path_split = $PATH_USER.Split(';')
+
+$EMSDK_Path_USER = $path_split | Where-Object { $_ -match 'emsdk' }
+if (!$EMSDK_Path_USER) {
+    throw "No path is added!"
+}
+$EMSDK_NODE_Path_USER = $path_split | Where-Object { $_ -match 'emsdk\\node' }
+if (!$EMSDK_NODE_Path_USER) {
+    throw "emsdk\node is not added to path."
+}
+$EMSDK_PYTHON_Path_USER = $path_split | Where-Object { $_ -match 'emsdk\\python' }
+if (!$EMSDK_PYTHON_Path_USER) {
+    throw "emsdk\python is not added to path."
+}
+$EMSDK_JAVA_Path_USER = $path_split | Where-Object { $_ -match 'emsdk\\java' }
+if (!$EMSDK_JAVA_Path_USER) {
+    throw "emsdk\java is not added to path."
+}
+
+$EMSDK_UPSTREAM_Path_USER = $path_split | Where-Object { $_ -match 'emsdk\\upstream\\emscripten' }
+if (!$EMSDK_UPSTREAM_Path_USER) {
+    throw "emsdk\upstream\emscripten is not added to path."
+}