package net.morilib.sh;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import net.morilib.sh.misc.FileTypeUtils;
import junit.framework.TestCase;

public class ShebangUtilsTest extends TestCase {

	public void eqs(String s, String p, String f, String a) {
		String[] x;

		try {
			x = FileTypeUtils.parseShebang(new ByteArrayInputStream(
					s.getBytes()));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		if(x == null)  fail();
		if(p == null)  assertNull(x[0]);
		if(p != null)  assertEquals(p, x[0]);
		if(f == null)  assertNull(x[1]);
		if(f != null)  assertEquals(f, x[1]);
		if(a == null)  assertNull(x[2]);
		if(a != null)  assertEquals(a, x[2]);
	}

	public void nil(String s) {
		String[] x;

		try {
			x = FileTypeUtils.parseShebang(new ByteArrayInputStream(
					s.getBytes()));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		assertNull(x);
	}

	public void testS001() {
		eqs("#! /bin/bash\n", "/bin", "bash", "");
	}

	public void testS002() {
		eqs("#! /bash\n", "/", "bash", "");
	}

	public void testS003() {
		eqs("#! /bin/awk -f\n", "/bin", "awk", "-f");
	}

	public void testS004() {
		eqs("#!/bin/awk -f\n", "/bin", "awk", "-f");
	}

	public void testS005() {
		eqs("#!    /bin/awk -f\n", "/bin", "awk", "-f");
	}

	public void testS006() {
		eqs("#! /bin/awk -f aaaa\n", "/bin", "awk", "-f aaaa");
	}

	public void testS007() {
		eqs("#! /bin/awk  \n", "/bin", "awk", "");
	}

	public void testS008() {
		eqs("#! /bin/bash\r", "/bin", "bash", "");
	}

	public void testS009() {
		eqs("#! /bash\r", "/", "bash", "");
	}

	public void testS010() {
		eqs("#! /bin/awk -f\r", "/bin", "awk", "-f");
	}

	public void testS011() {
		eqs("#!/bin/awk -f\r", "/bin", "awk", "-f");
	}

	public void testS012() {
		eqs("#!    /bin/awk -f\r", "/bin", "awk", "-f");
	}

	public void testS013() {
		eqs("#! /bin/awk -f aaaa\r", "/bin", "awk", "-f aaaa");
	}

	public void testS014() {
		eqs("#! /bin/awk  \r", "/bin", "awk", "");
	}

	public void testS015() {
		eqs("#! /usr/local/bin/perl -f\n", "/usr/local/bin", "perl", "-f");
	}

	public void testS401() {
		nil("");
	}

	public void testS402() {
		nil("#! /bin/sh");
	}

	public void testS403() {
		nil("#\n");
	}

	public void testS404() {
		nil("#!\n");
	}

	public void testS405() {
		nil("#!  \n");
	}

	public void testS406() {
		nil("#! /\u0080a/sh\n");
	}

	public void testS407() {
		nil("#! /bin/\u0080sh\n");
	}

	public void testS408() {
		nil("#! /bin/sh \u0080\n");
	}

	public void testS409() {
		nil("#! /bin/sh -f\u0080\n");
	}

	public void testS410() {
		nil("#! /bin/awk\u0002\n");
	}

	public void testS411() {
		nil("#! /bin/awk \u0002\n");
	}

	public void testS412() {
		nil("#! /bin/awk -f\u0002\n");
	}

}
