/*
 * 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.builtin;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Iterator;

import net.morilib.sh.ShEnvironment;
import net.morilib.sh.ShFile;
import net.morilib.sh.ShFileSystem;
import net.morilib.sh.ShProcess;
import net.morilib.unix.misc.OptionIterator;

public class ShMkdir implements ShProcess {

	private static final int PARENT = 1;

	public int main(ShEnvironment env, ShFileSystem fs, InputStream in,
			PrintStream out, PrintStream err,
			String... args) throws IOException {
		String[] a = new String[args.length - 1], b;
		Iterator<String> t;
		OptionIterator o;
		int f = 0;
		String s;
		ShFile r;

		System.arraycopy(args, 1, a, 0, a.length);
		o  = new OptionIterator("p", a);
		while(o.hasNext()) {
			switch(o.nextChar()) {
			case 'p':  f |= PARENT;  break;
			default:
				err.print("mkdir: unrecognized option: ");
				err.println((char)o.getErrorOption());
				return 2;
			}
		}

		t = o.filenameIterator();
		while(t.hasNext()) {
			s = t.next();
			if((f & PARENT) != 0) {
				if(s.length() == 0) {
					continue;
				} else if(s.charAt(0) == '/') {
					s = s.replaceFirst("^/+", "");
					r = fs.getRoot();
				} else {
					r = fs.getCurrentDirectory();
				}

				s = s.replaceFirst("/+$", "");
				b = s.split("/+");
				for(String x : b) {
					r = fs.getFile(r, x);
					if(r.isDirectory()) {
						// do nothing
					} else if(!r.mkdir()) {
						err.print("mkdir: cannot make directory `");
						err.print(r.toString());
						err.println("'");
						return 2;
					}
				}
			} else if(!fs.getFile(s).mkdir()) {
				err.print("mkdir: cannot make directory `");
				err.print(s);
				err.println("'");
				return 2;
			}
		}
		return 0;
	}

}
