/*******************************************************************************
 *  Copyright (c) 2005, 2009 IBM Corporation and others.
 *
 *  This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License 2.0
 *  which accompanies this distribution, and is available at
 *  https://www.eclipse.org/legal/epl-2.0/
 *
 *  SPDX-License-Identifier: EPL-2.0
 * 
 *  Contributors:
 *      IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.equinox.p2.tests.engine;

import java.io.*;
import java.nio.channels.FileLock;

/**
 * 
 * This is a tiny console app used by {@link ProfileRegistryTest#testProfileLocking()},
 * to simulate an external locking mechanism that is triggered as a new process. This
 * code is invoked via the jar file kept in testData/engineTest/SimpleFileLockerApp.jar,
 * which is generated by exporting this single class as a JAR.
 */
public class SimpleFileLockerApp {
	File lockFile;
	RandomAccessFile raf;
	FileLock lock;

	SimpleFileLockerApp(File lock) {
		lockFile = lock;
	}

	void create() {
		try {
			raf = new RandomAccessFile(lockFile, "rw"); //$NON-NLS-1$
			String lockMode = System.getProperty("osgi.locking"); //$NON-NLS-1$
			lockMode = (lockMode == null || lockMode.length() == 0) ? "java.nio" : lockMode; //$NON-NLS-1$
			if ("java.io".equalsIgnoreCase(lockMode)) { //$NON-NLS-1$
				raf.writeByte(0);
			} else {
				lock = raf.getChannel().tryLock(0, 1, false);
			}
		} catch (FileNotFoundException e) {
			remove();
			e.printStackTrace();
		} catch (IOException e) {
			remove();
			e.printStackTrace();
		}
	}

	void remove() {
		if (raf != null) {
			try {
				if (lock != null) {
					lock.release();
				}
				raf.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			raf = null;
			lockFile.delete();
		}
	}

	public static void main(String[] args) {
		final String LOCK_FILENAME = ".lock"; //$NON-NLS-1$
		if (args == null || args.length < 1) {
			throw new IllegalArgumentException("Should have at least one arg - path."); //$NON-NLS-1$
		}
		File lockDir = new File(args[0]);
		lockDir.mkdir();
		SimpleFileLockerApp extLock = new SimpleFileLockerApp(new File(lockDir, LOCK_FILENAME));
		File waitUntil = new File(lockDir, ".done"); //$NON-NLS-1$
		waitUntil.delete();

		extLock.create();

		final int MAX_RETRIES; // A guard against looping indefinitely!
		if (args.length > 1) {
			MAX_RETRIES = getMax(args[1]);
		} else {
			MAX_RETRIES = 20;
		}
		int attempts = 0;
		while (attempts++ < MAX_RETRIES && !waitUntil.exists()) {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		extLock.remove();
		extLock = null;

		waitUntil.delete();

	}

	private static int getMax(String str) {
		int num = 20;
		try {
			num = Integer.parseInt(str);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return num;
	}
}
