/*
 * Copyright 2017 Lukáš Petrovický
 *
 * 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 com.github.triceo.robozonky.app;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.Optional;
import java.util.function.Consumer;

import com.github.triceo.robozonky.api.ReturnCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Used to ensure that only one RoboZonky process may be executing at any one time. See {@link #get()} for the
 * contract. Will not mutually exclude RoboZonky instances running within the same JVM.
 */
final class Exclusivity implements ShutdownHook.Handler {

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

    private final File fileToLock;
    private FileLock lock = null;

    /**
     * Guarantees exclusivity based on a randomly created temp file. This is only useful for testing, since in all
     * other cases multiple JVMs need to synchronize around the same file.
     * @throws IOException When the temp file could not be created.
     */
    Exclusivity() throws IOException {
        this(File.createTempFile("robozonky-", ".lock"));
    }

    /**
     * Guarantees exclusivity around a provided file.
     * @param lock File to lock on.
     */
    public Exclusivity(final File lock) {
        this.fileToLock = lock;
    }

    File getFileToLock() {
        return this.fileToLock;
    }

    /**
     * Whether or not the application has managed to acquire exclusivity.
     * @return  True between any two successful successive calls to {@link #ensure()} and {@link #waive()} respectively.
     * Will be false before first successful {@link #ensure()} or after every {@link #waive()}.
     */
    synchronized boolean isEnsured() {
        return lock != null && lock.isValid() && !lock.isShared();
    }

    /**
     * Allow other instances of RoboZonky to run, possibly acquiring exclusivity for themselves.
     */
    synchronized void waive() {
        if (!this.isEnsured()) {
            Exclusivity.LOGGER.debug("Already waived.");
            return;
        }
        try {
            this.lock.release();
            Exclusivity.LOGGER.debug("File lock released.");
        } catch (final IOException ex) {
            Exclusivity.LOGGER.warn("Failed releasing lock, new RoboZonky processes may not launch.", ex);
        } finally {
            Exclusivity.LOGGER.debug("Lock file deleted successfully: {}.", this.fileToLock.delete());
        }
    }

    /**
     * Will return after this instance of RoboZonky has acquired exclusivity, or failed. May block for extensive periods
     * of time. Make sure to call {@link #isEnsured()} afterwards to see if exclusivity is ensured.
     */
    synchronized void ensure() {
        if (this.isEnsured()) {
            Exclusivity.LOGGER.debug("Already ensured.");
            return;
        }
        Exclusivity.LOGGER.info("Checking we're the only RoboZonky running.");
        Exclusivity.LOGGER.debug("Acquiring file lock: {}.", this.fileToLock.getAbsolutePath());
        try {
            final FileChannel ch = new RandomAccessFile(this.fileToLock, "rw").getChannel();
            this.lock = ch.lock();
            Exclusivity.LOGGER.debug("File lock acquired.");
        } catch (final IOException ex) {
            Exclusivity.LOGGER.error("Failed acquiring lock, another RoboZonky process likely running.", ex);
        }
    }

    /**
     * Call in order to acquire exclusivity. May block for extensive periods of time until exclusivity is acquired.
     * @return If present, call in order to waive exclusivity. If empty, exclusivity not acquired.
     */
    @Override
    public Optional<Consumer<ReturnCode>> get() {
        this.ensure();
        if (!this.isEnsured()) {
            return Optional.empty();
        } else { // other RoboZonky instances can now start executing
            return Optional.of((code) -> this.waive());
        }
    }
}

@@ -722,46 +722,8 @@
 le;%0A
-import java.nio.channels.FileChannel;%0A
 impo
@@ -1294,56 +1294,649 @@
 ate 
-final File fileToLock;%0A    private FileLock lock
+static final class LockControl %7B%0A%0A        private final RandomAccessFile randomAccessFile;%0A        private final FileLock lock;%0A%0A        public LockControl(final File lockedFile) throws IOException %7B%0A            this.randomAccessFile = new RandomAccessFile(lockedFile, %22rw%22);%0A            this.lock = this.randomAccessFile.getChannel().lock();%0A        %7D%0A%0A        public boolean hasValidLock() %7B%0A            return lock.isValid();%0A        %7D%0A%0A        public void invalidateLock() throws IOException %7B%0A            this.randomAccessFile.close();%0A        %7D%0A%0A    %7D%0A%0A    private final File fileToLock;%0A    private Exclusivity.LockControl lockControl
  = n
@@ -2937,16 +2937,23 @@
 urn lock
+Control
  != null
@@ -2964,36 +2964,28 @@
 lock
-.isValid() && !lock.isShared
+Control.hasValidLock
 ();%0A
@@ -3295,16 +3295,30 @@
 lock
-.release
+Control.invalidateLock
 ();%0A
@@ -4262,121 +4262,70 @@
     
-final FileChannel ch = new RandomAccessFile(this.fileToLock, %22rw%22).getChannel();%0A            this.lock = ch.l
+this.lockControl = new Exclusivity.LockControl(this.fileToL
 ock
-(
 );%0A 

Fix locking on Windows