/*
 * 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.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Iterator;

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

public class ShRm implements ShProcess {

	private static final int FORCE = 1;
	private static final int INTERACTIVE = 2;
	private static final int VERBOSE = 4;

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

		System.arraycopy(args, 1, a, 0, a.length);
		o = new OptionIterator("firv", a);
		while(o.hasNext()) {
			if(o.getLookahead().equals("--interactive")) {
				f |= INTERACTIVE;
				o.nextChar();
			} else if(o.getLookahead().equals("--force")) {
				f |= FORCE;
				o.nextChar();
			} else if(o.getLookahead().equals("--recursive")) {
				err.print("rm: removing recursively");
				err.println(" is not supported.");
				return 2;
			} else if(o.getLookahead().equals("--verbose")) {
				f |= VERBOSE;
				o.nextChar();
			} else {
				switch(o.nextChar()) {
				case 'f':  f |= FORCE;  break;
				case 'i':  f |= INTERACTIVE;  break;
				case 'v':  f |= VERBOSE;  break;
				case 'r':
					err.print("rm: removing recursively");
					err.println(" is not supported.");
					return 2;
				default:
					err.print("rm: unrecognized option: ");
					err.println((char)o.getErrorOption());
					return 2;
				}
			}
		}

		t  = o.filenameIterator();
		rd = new BufferedReader(new InputStreamReader(in));
		while(t.hasNext()) {
			s = t.next();
			if((f & INTERACTIVE) != 0) {
				err.print("rm: remove file `");
				err.print(s);
				err.print("'? ");
				if(!(x = rd.readLine()).equalsIgnoreCase("y") &&
						!x.equalsIgnoreCase("yes")) {
					continue;
				}
			}
			if((f & VERBOSE) != 0)  out.println(s);
			if(!fs.getFile(s).deleteFile()) {
				err.print("rm: cannot remove `");
				err.print(s);
				err.println("'.");
				r = 2;
			}
		}
		return r;
	}

}
