/*
 * 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 java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.morilib.sh.Sh;
import net.morilib.sh.ShFileSystem;
import net.morilib.sh.ShProcess;
import net.morilib.sh.misc.FileTypeUtils;

public class ShUnixRealFile extends ShRealFile {

	public ShUnixRealFile(ShFileSystem fs, String virtualpath,
			File file) {
		super(fs, virtualpath, file);
	}

	public ShProcess getProcess(String... args) {
		ProcessBuilder p;
		List<String> l;
		String[] a;

		if(FileTypeUtils.guessUnixExecutable(file).isExecutable()) {
			if(filesystem.getSecurityPolicy().denyExecuteOSCommand()) {
				return null;
			}
			l = new ArrayList<String>(Arrays.asList(args));
			l.set(0, filesystem.getFile(l.get(0)).toString());
			p = new ProcessBuilder(l);
			return new ShOSProcess(p);
		} else if((a = FileTypeUtils.parseShebang(file)) != null &&
				a[1].equals(Sh.NAME)) {
			// TODO execute a script of this shell
			return null;
		} else if(a != null && a[0] != null && a[1] != null) {
			// TODO #! line
//			l = new ArrayList<String>();
//			l.add(a[0] + (a[0].equals("/") ? "" : "/") + a[1]);
//			if(a[2].length() > 0)  l.add(a[2]);
//			l.addAll(Arrays.asList(args));
//			p = new ProcessBuilder(l);
//			return new ShOSProcess(p);
			return null;
		} else {
			return null;
		}
	}

	public boolean isExecutable() {
		return file.canExecute();
	}

}
