/*
 * Copyright (C) 2024- 2025 ScalAgent Distributed Technologies
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA.
 *
 * Initial developer(s): ScalAgent Distributed Technologies
 * Contributor(s): 
 */
package fr.dyade.aaa.agent;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

import fr.dyade.aaa.common.Debug;

public class ServerLock {
  private static Logger logger = Debug.getLogger(AgentServer.class.getName());
  private static final boolean DEBUG = logger.isLoggable(BasicLevel.DEBUG);

  private RandomAccessFile raf;
  private FileLock lock;
  
  public ServerLock(File file) throws IOException {
    raf = new RandomAccessFile(file, "rw");
    lock = raf.getChannel().tryLock();
    if (lock == null)
      throw new IOException("Cannot acquire lock.");
    file.deleteOnExit();
  }

  public void check() {
    if (lock != null)
      logger.log(BasicLevel.WARN, "AgentServer.lock -> " + lock.isValid() + '/' + lock.isShared());
  }
  
  public void close() {
    try {
      if (lock != null)
        lock.release();
    } catch (IOException exc) {
      if (DEBUG)
        logger.log(BasicLevel.WARN, "Cannot release AgentServer lock.", exc);
      else
        logger.log(BasicLevel.WARN, "Cannot release AgentServer lock: " + exc.getMessage());
    } finally {
      lock = null;
    }
    try {
      if (raf != null)
        raf.close();
    } catch (IOException exc) {
      if (DEBUG)
        logger.log(BasicLevel.WARN, "Cannot close AgentServer lock.", exc);
      else
        logger.log(BasicLevel.WARN, "Cannot close lock: " + exc.getMessage());
    } finally {
      raf = null;
    }
  }
}
