/*
 * Copyright (C) FuseSource, Inc.
 *   http://fusesource.com
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package org.fusesource.fabric.git.internal;

import java.io.IOException;

import org.apache.curator.framework.CuratorFramework;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.StoredConfig;
import org.fusesource.fabric.git.GitNode;
import org.fusesource.fabric.groups.Group;
import org.fusesource.fabric.groups.GroupListener;
import org.fusesource.fabric.groups.internal.ZooKeeperGroup;
import org.fusesource.fabric.git.FabricGitService;
import org.fusesource.fabric.utils.Closeables;
import org.fusesource.fabric.zookeeper.ZkPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.fusesource.fabric.zookeeper.utils.ZooKeeperUtils.getSubstitutedData;

@Component(name = "org.fusesource.fabric.git.service", description = "Fabric Git Service", immediate = true)
@Service(FabricGitService.class)
public class FabricGitServiceImpl implements FabricGitService, GroupListener<GitNode> {

    private static final Logger LOGGER = LoggerFactory.getLogger(FabricGitServiceImpl.class);

    @Reference(cardinality = org.apache.felix.scr.annotations.ReferenceCardinality.MANDATORY_UNARY)
	private CuratorFramework curator;

    @Reference(cardinality = org.apache.felix.scr.annotations.ReferenceCardinality.MANDATORY_UNARY)
	private GitService gitService;

    private Group<GitNode> group;

    @Activate
    public void init() {
        group = new ZooKeeperGroup<GitNode>(curator, ZkPath.GIT.getPath(), GitNode.class);
        group.add(this);
        group.start();
    }

    @Deactivate
    public void destroy() {
        Closeables.closeQuitely(group);
        group = null;
    }

    public Git get() throws IOException {
        return gitService.get();
    }

    @Override
    public void groupEvent(Group<GitNode> group, GroupEvent event) {
        String masterUrl = null;
		GitNode master = group.master();
		if (master != null
                && !master.getContainer().equals(System.getProperty("karaf.name"))) {
            masterUrl = master.getUrl();
        }
		try {
            Git git = get();
            StoredConfig config = git.getRepository().getConfig();
            if (masterUrl != null) {
                String currentMasterUrl = config.getString("remote", "origin", "url");
                if (!masterUrl.equals(currentMasterUrl)) {
                    config.setString("remote", "origin", "url", getSubstitutedData(curator, masterUrl));
                    config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
                    fireRemoteChangedEvent();
                }
            } else {
                config.unsetSection("remote", "origin");
            }
			config.save();
		} catch (Exception e) {
			LOGGER.error("Failed to point origin to the new master.", e);
		}
	}

    private void fireRemoteChangedEvent() {
        if (gitService != null) {
            gitService.onRemoteChanged();
        }
    }
}

@@ -1387,16 +1387,69 @@
 eables;%0A
+import org.fusesource.fabric.utils.SystemProperties;%0A
 import o
@@ -2722,24 +2722,350 @@
 nt event) %7B%0A
+        switch (event) %7B%0A            case CONNECTED:%0A            case CHANGED:%0A                updateMasterUrl(group);%0A                break;%0A            case DISCONNECTED:%0A        %7D%0A%09%7D%0A%0A    /**%0A     * Updates the git master url, if needed.%0A     * @param group%0A     */%0A    private void updateMasterUrl(Group%3CGitNode%3E group) %7B%0A
         Stri
@@ -3085,18 +3085,24 @@
 = null;%0A
-%09%09
+        
 GitNode 
@@ -3126,18 +3126,24 @@
 ster();%0A
-%09%09
+        
 if (mast
@@ -3225,20 +3225,35 @@
 rty(
-%22karaf.name%22
+SystemProperties.KARAF_NAME
 ))) 
@@ -3305,18 +3305,24 @@
       %7D%0A
-%09%09
+        
 try %7B%0A  
@@ -3965,19 +3965,28 @@
       %7D%0A
-%09%09%09
+            
 config.s
@@ -3992,18 +3992,24 @@
 save();%0A
-%09%09
+        
 %7D catch 
@@ -4028,11 +4028,20 @@
 ) %7B%0A
-%09%09%09
+            
 LOGG
@@ -4102,13 +4102,22 @@
 e);%0A
-%09%09%7D%0A%09
+        %7D%0A    
 %7D%0A%0A 

Fix NPE when disconnecting.