// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.version;

import com.google.inject.Inject;
import com.yahoo.cloud.config.ConfigserverConfig;
import com.yahoo.component.Version;
import com.yahoo.io.IOUtils;
import com.yahoo.path.Path;
import com.yahoo.text.Utf8;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.defaults.Defaults;
import com.yahoo.vespa.flags.BooleanFlag;
import com.yahoo.vespa.flags.FlagSource;
import com.yahoo.vespa.flags.Flags;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Optional;

/**
 *
 * Contains version information for this configserver. Stored both in file system and in ZooKeeper (uses
 * data in ZooKeeper if distributeApplicationPackage and data found in ZooKeeper)
 *
 * @author Ulf Lilleengen
 */
public class VersionState {

    static final Path versionPath = Path.fromString("/config/v2/vespa_version");

    private final File versionFile;
    private final Curator curator;
    private final BooleanFlag distributeApplicationPackage;

    @Inject
    public VersionState(ConfigserverConfig config, Curator curator, FlagSource flagsource) {
        this(new File(Defaults.getDefaults().underVespaHome(config.configServerDBDir()), "vespa_version"), curator, flagsource);
    }

    public VersionState(File versionFile, Curator curator, FlagSource flagSource) {
        this.versionFile = versionFile;
        this.curator = curator;
        this.distributeApplicationPackage = Flags.CONFIGSERVER_DISTRIBUTE_APPLICATION_PACKAGE.bindTo(flagSource);
    }

    public boolean isUpgraded() {
        System.out.println("current version: " + currentVersion() + ", stored version: " + storedVersion());
        return currentVersion().compareTo(storedVersion()) > 0;
    }

    public void saveNewVersion() {
        saveNewVersion(currentVersion().toFullString());
    }

    public void saveNewVersion(String vespaVersion) {
        curator.set(versionPath, Utf8.toBytes(vespaVersion));
        try (FileWriter writer = new FileWriter(versionFile)) {
            writer.write(vespaVersion);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public Version storedVersion() {
        if (distributeApplicationPackage.value()) {
            Optional<byte[]> version = curator.getData(versionPath);
            if(version.isPresent()) {
                System.out.println("Found version in zk ");
                try {
                    return Version.fromString(Utf8.toString(version.get()));
                } catch (Exception e) {
                    return new Version(0, 0, 0); // Use an old value to signal we don't know
                }
            }
        }
        try (FileReader reader = new FileReader(versionFile)) {
            System.out.println("Found version in file ");
            return Version.fromString(IOUtils.readAll(reader));
        } catch (Exception e) {
            return new Version(0, 0, 0); // Use an old value to signal we don't know
        }
    }

    public Version currentVersion() {
        return new Version(VespaVersion.major, VespaVersion.minor, VespaVersion.micro);
    }

    File versionFile() {
        return versionFile;
    }

    @Override
    public String toString() {
        return String.format("Current version:%s, stored version:%s", currentVersion(), storedVersion());
    }

}

@@ -1723,117 +1723,8 @@
 ) %7B%0A
-        System.out.println(%22current version: %22 + currentVersion() + %22, stored version: %22 + storedVersion());%0A
     
@@ -2403,68 +2403,8 @@
 ) %7B%0A
-                System.out.println(%22Found version in zk %22);%0A
     
@@ -2562,80 +2562,38 @@
     
-return new Version(0, 0, 0); // Use an old value to signal we don't know
+// continue, use value in file
 %0A   
@@ -2699,66 +2699,8 @@
 ) %7B%0A
-            System.out.println(%22Found version in file %22);%0A
     

Remove debug logging and fallback to file if we fail to read from zk