/*
 * Copyright 2013 Yuichiro Moriguchi
 *
 * 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 net.morilib.sh.file;

import net.morilib.sh.ShEnvironment;
import net.morilib.sh.ShFileSystem;
import net.morilib.sh.ShSecurityPolicy;
import net.morilib.sh.misc.OSInfo;

public class ShFileSystemFactory {

	private static final ShSecurityPolicy A =
		ShSecurityPolicy.ALL_PERMITTED;
	private static ShFileSystem instance = null;

	/**
	 * 
	 * @return
	 */
	public synchronized static ShFileSystem getInstance() {
		StringBuffer b;
		String s, d;

		if(instance != null) {
			// do nothing
		} else if(OSInfo.OS.isWindows()) {
			if((s = System.getenv("JSHHOME")) != null) {
				instance = new ShWindowsFileSystem(s, A);
			} else if((d = System.getenv("HOMEDRIVE")) == null ||
					(s = System.getenv("HOMEPATH")) == null ||
					d.length() < 1) {
				instance = new ShWindowsFileSystem("/", A);
			} else {
				b = new StringBuffer("/");
				b.append(Character.toLowerCase(d.charAt(0)));
				b.append('/');
				b.append(s.replace('\\', '/'));
				instance = new ShWindowsFileSystem(b.toString(), A);
			}
		} else if(OSInfo.OS.isUNIX()) {
			if((s = System.getenv("JSHHOME")) != null) {
				instance = new ShUnixFileSystem(s, A);
			} else if((s = System.getenv("HOME")) != null) {
				instance = new ShUnixFileSystem(s, A);
			} else {
				instance = new ShUnixFileSystem("/", A);
			}
		} else {
			if((s = System.getenv("JSHHOME")) != null) {
				instance = new ShUnixFileSystem(s, A);
			} else {
				instance = new ShUnixFileSystem("/", A);
			}
		}
		return instance;
	}

	/**
	 * 
	 * @return
	 */
	public static ShEnvironment getSystemEnvironment() {
		ShEnvironment env;

		if(OSInfo.OS.isWindows()) {
			env = new ShWindowsEnvironment();
		} else if(OSInfo.OS.isUNIX()) {
			env = new ShUnixEnvironment();
		} else {
			env = new ShUnixEnvironment();
		}
		env.bind("IFS", " ");
		return env;
	}

}
