/*
 * 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.nina.translate.sh;

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.ShFileGetter;
import net.morilib.sh.ShFileSystem;
import net.morilib.sh.ShProcess;
import net.morilib.unix.misc.OptionIterator;

public class ShSed implements ShProcess {

	//
	int main(ShEnvironment env, ShFileSystem fs, ShFileGetter gt,
			InputStream in, PrintStream out, PrintStream err,
			String... args) throws IOException {
		Reader rd = null, rc;
		SedPatternEngine en;
		Iterator<String> t;
		OptionIterator o;
		boolean n = true;
		InputStream ins;
		int r = 0, x;
		String s;

		o  = new OptionIterator("ne:f:", args);
		while(o.hasNext()) {
			switch(o.nextChar()) {
			case 'n':  n = false;  break;
			case 'e':
				rd = new StringReader(o.getArgument());
				break;
			case 'f':
				rd = new InputStreamReader(
						gt.get(fs, o.getArgument()).getInputStream(),
						env.getCharset());
				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 : gt.get(fs, s).getInputStream();
				rc  = new InputStreamReader(ins, env.getCharset());
				x   = Sed.execute(fs, rd, rc, out, en, n);
				r   = x == 0 ? r : x;
			}
			return r;
		} else {
			rc = new InputStreamReader(in, env.getCharset());
			return Sed.execute(fs, rd, rc, out, en, n);
		}
	}

	/* (non-Javadoc)
	 * @see net.morilib.sh.ShProcess#main(net.morilib.sh.ShEnvironment, net.morilib.sh.ShFileSystem, java.io.InputStream, java.io.PrintStream, java.io.PrintStream, java.lang.String[])
	 */
	public int main(ShEnvironment env, ShFileSystem fs, InputStream in,
			PrintStream out, PrintStream err,
			String... args) throws IOException {
		String[] a = new String[args.length - 1];

		System.arraycopy(args, 1, a, 0, a.length);
		return main(env, fs, ShFileGetter.SH_FILE, in, out, err, a);
	}

}
