package org.maachang.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 環境変数を取得.
 * 
 * @version 2008/11/05
 * @author masahito suzuki
 * @since MaachangBase 1.08
 */
public abstract class EnvName {
    private EnvName() {}
    
    /**
     * 指定環境変数内容を取得.
     * @param name 対象の名前を設定します.
     * @return String 環境変数情報が返されます.
     * @exception Exception 例外.
     */
    public static final String getEnv( String name )
        throws Exception {
        if( name == null || ( name = name.trim() ).length() <= 0 ) {
            throw new IllegalArgumentException( "引数は不正です" ) ;
        }
        switch( Os.getInstance().getOS() ) {
            case Os.OS_WINNT :
                return getEnvNt( name ) ;
            case Os.OS_UNIX :
            case Os.OS_MAC_OS_X :
                return getEnvUnix( name ) ;
        }
        throw new IOException( "実行中のOSでは利用できません" ) ;
    }
    
    /**
     * env for WindowsNT.
     */
    private static final String getEnvNt( String name ) throws Exception {
        String ret = null ;
        String[] cmd = new String[]{ "cmd","/c","echo %"+name+"%" } ;
        RunProcess runProc = new RunProcess( cmd ) ;
        try {
            BufferedReader reader = new BufferedReader( new InputStreamReader( runProc.execution() ) ) ;
            for( ;; ) {
                String s = reader.readLine() ;
                if( s == null ) {
                    break ;
                }
                ret = s ;
                break ;
            }
            runProc.waitFor() ;
        } finally {
            runProc.destroy() ;
        }
        return ret ;
    }
    
    /**
     * env for Unix.
     */
    private static final String getEnvUnix( String name ) throws Exception {
        String ret = null ;
        String[] cmd = new String[]{ "/bin/sh","-c","/bin/echo ${"+name+"}" } ;
        RunProcess runProc = new RunProcess( cmd ) ;
        try {
            BufferedReader reader = new BufferedReader( new InputStreamReader( runProc.execution() ) ) ;
            for( ;; ) {
                String s = reader.readLine() ;
                if( s == null ) {
                    break ;
                }
                ret = s ;
                break ;
            }
            runProc.waitFor() ;
        } finally {
            runProc.destroy() ;
        }
        return ret ;
    }
    
    /** test. */
    public static final void main( String[] args ) throws Exception {
        BufferedReader r = new BufferedReader( new InputStreamReader( System.in ) ) ;
        for( ;; ) {
            System.out.print( "env>" ) ;
            String name = r.readLine() ;
            if( name == null ) {
                break ;
            }
            if((name=name.trim()).length() <= 0) {
                continue ;
            }
            System.out.println( "[" + name + "]:" + getEnv( name ) ) ;
        }
    }
}
