/*
 * 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.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.Iterator;

import net.morilib.sed.Sed;
import net.morilib.sed.SedBasicRegexEngine;
import net.morilib.sed.SedPatternEngine;
import net.morilib.sh.ShEnvironment;
import net.morilib.sh.ShFileSystem;
import net.morilib.sh.ShProcess;
import net.morilib.unix.misc.OptionIterator;

public class ShSed implements ShProcess {

	public int main(ShEnvironment env, ShFileSystem fs, InputStream in,
			PrintStream out, PrintStream err,
			String... args) throws IOException {
		String[] a = new String[args.length - 1];
		Reader rd = null, rc;
		SedPatternEngine en;
		Iterator<String> t;
		OptionIterator o;
		boolean n = true;
		InputStream ins;
		int r = 0, x;
		String s;

		System.arraycopy(args, 1, a, 0, a.length);
		o  = new OptionIterator("ne:f:", a);
		while(o.hasNext()) {
			switch(o.nextChar()) {
			case 'n':  n = false;  break;
			case 'e':
				rd = new StringReader(o.getArgument());
				break;
			case 'f':
				rd = new InputStreamReader(
						fs.getFile(o.getArgument()).getInputStream());
				break;
			}
		}

		en = SedBasicRegexEngine.getInstance();
		t  = o.filenameIterator();
		if(rd != null) {
			// do nothing
		} else if(t.hasNext()) {
			rd = new StringReader(t.next());
		} else {
			err.println("sed: missing script");
			return 2;
		}

		if(t.hasNext()) {
			while(t.hasNext()) {
				s   = t.next();
				ins = s.equals("-") ?
						in : fs.getFile(s).getInputStream();
				rc  = new InputStreamReader(ins);
				x   = Sed.execute(fs, rd, rc, out, en, n);
				r   = x == 0 ? r : x;
			}
			return r;
		} else {
			rc = new InputStreamReader(in);
			return Sed.execute(fs, rd, rc, out, en, n);
		}
	}

}
