:

mydir=$1
tls_ok=''

old="$tls_dir"
tls_dir=''
tls_include_dir=''
tls_lib_dir=''

while $test "$tls_ok" = "" ; do

    for a in $old /usr/local/ssl /usr/local trysystem none; do
	case "$tls_dir" in 
	'')
		case "$a" in
			none)
			tls_dir=none
			;;
			system)
			tls_dir=system
			;;

			trysystem)

			foundlibssl=''
			

			if $test -f /etc/ld.so.conf ; then
			    lddirs="`awk '/^\/.*/' /etc/ld.so.conf`"
			    ldsoinclude="`awk '$1 ~ /^include$/ { print $2; }' /etc/ld.so.conf`"
			    
			    if $test "$ldsoinclude" != "" ; then
				
				for j in $ldsoinclude ; do
				    case "$j" in
					/*)
					    XX="`awk '/^\/.*/' $j`"
					    if $test "$XX" != "" ; then
						lddirs="$lddirs $XX"
					    fi
					    ;;
					*)
					    XX="`awk '/^\/.*/' /etc/$j`"
					    if $test "$XX" != "" ; then
						lddirs="$lddirs $XX"
					    fi
					    ;;

				    esac
				done
			    fi

			    for d in $lddirs ; do
				if $test "`$ls $d/libssl.* 2>/dev/null`" != "" 
				then
				    foundlibssl="$d"
				fi
			    done

			fi

			if $test -r /usr/include/openssl/ssl.h -a \
				 "$foundlibssl" != ""
			then
			    tls_dir=system
			    echo "Found OpenSSL from system directory"
			elif $test -r /usr/include/openssl/ssl.h -a \
				   "`$ls /usr/$libdirname/libssl.* 2>/dev/null`" != "" 
			then
			    tls_dir=system
			    echo "Found OpenSSL from system directory"
			elif $test -r /usr/include/openssl/ssl.h -a  \
				   "`$ls /usr/lib/libssl.* 2>/dev/null`" != "" 
			then
			    tls_dir=system
			    echo "Found OpenSSL from system directory"
                        elif $test -r /usr/include/openssl/ssl.h -a \
				   "$found_libcso" != ""
			then 
                            d="`$dirname \"$found_libcso\"`"
                            
			    if $test "`$ls $d/libssl.* 2>/dev/null`" != "" 
                            then
				tls_dir=system
				echo "Found OpenSSL from system directory"
                            fi                             
			fi

			;;

			*)
			if $test -r $a/include/openssl/ssl.h -a \
                            "`$ls $a/$libdirname/libssl.* 2>/dev/null`" != "" 
			then
				tls_dir="$a"
				echo "Found OpenSSL from $tls_dir"
			elif $test -r $a/include/openssl/ssl.h -a  \
			   "`$ls $a/lib/libssl.* 2>/dev/null`" != "" 
			then
				tls_dir="$a"
				echo "Found OpenSSL from $tls_dir"
			fi
			;;
		esac
	;;
	esac
    done

    cat <<EOM

Elm ME+ can use OpenSSL library for TLS support. Support is
implemented as shared library libelmme-tls.so. Give directory
under which there are library and include files of OpenSSL. Give "none"
to disable generation of shared library. Give "system" to indicate
that OpenSSL include and library files are search path of compiler.

EOM
    dflt="$tls_dir"

    rp="OpenSSL directory prefix? [$dflt]"
    echo $n "$rp $c"
    . myread

    case "$ans" in
	none)
	    tls_dir=none
	    tls_ok="$undef"
	    echo "TLS disabled"
	;;
	system)
	    tls_include_dir=''
	    tls_lib_dir=''
	    tls_dir=system
	    tls_ok="$define"
	    echo "OpenSSL is assumed to found from system locations"
	;;
	*)
	    tls_dir="$ans"
	    tls_include_dir="$tls_dir/include"
	    X="`$ls $tls_dir/$libdirname/libssl.* 2>/dev/null`"
	    if $test "$X" != ""
	    then
		tls_lib_dir="$tls_dir/$libdirname"
	    else
	    	tls_lib_dir="$tls_dir/lib"
	    fi
	    tls_ok="$define"
	    echo "OpenSSL is assumed to found from $tls_dir directory"
	;;
   esac

   if $test "$tls_ok" = "$define"; then
	$cat >try.c <<'EOF'
#include <stdio.h>

#if defined(__STDC__)
#include <stdlib.h>

int main (int argc, char * argv[]);
#else

#ifndef const
#define const
#endif
#endif

#include <openssl/ssl.h>

int main(argc,argv)
    int argc;
    char **argv;
{

    SSL_load_error_strings(); 
    SSL_library_init();

    return 0;
}
EOF
   
	rpathlist=''
	linklist=''
	if $test "$tls_lib_dir" != "" ; then
	    linklist="-L$tls_lib_dir"
	    rpathlist="$rpath_opt$tls_lib_dir"
	fi

	inclist=''
	if $test "$tls_include_dir" != "" ; then
	    inclist="-I$tls_include_dir"
	fi

	if $cc $ccflags -o try $inclist $linklist $rpathlist try.c -lssl -lcrypto > try.log 2>&1
	then
	    echo "Test compilation with OpenSSL succeed..."

	    if ./try ; then
		echo "Calling of OpenSSL succeed..."
	    else
		tls_ok=''
		echo "Calling of OpenSSL failed..."
	    fi

	else
	    tls_ok=''
	    echo "Failed to compile and link with OpenSSL".
	    # cat try.log
	fi

	rm -f try.log try.c try

	case "$tls_ok" in
	'')
	    cat <<EOF

OpenSSL location $tls_dir seems not work. Select on of following
    d) Disable TLS support
    c) Change OpenSSL directory prefix

EOF
	    dflt=d
	    rp="Your selection? [$dflt]"
	    echo $n "$rp $c"
	    . myread

	    if $test "$ans" = d; then
		tls_dir=none
		tls_ok="$undef"
		echo "TLS disabled"	
	    fi
	;;
	esac
    fi
done

tls_have_egd="$undef"

cp -f /dev/null "$build_dir/$mydir/testresult" || exit 1 

if $test "$tls_ok" = "$define"; then		

    $echo $n "Testing linking of RAND_egd_bytes() ... $c"

    $cat >tryegd.c <<'EOF'
#include <stdio.h>

#if defined(__STDC__)
#include <stdlib.h>

int main (int argc, char * argv[]);
#else

#ifndef const
#define const
#endif
#endif

#include <openssl/ssl.h>
#include <openssl/rand.h>

int main(argc,argv)
    int argc;
    char **argv;
{

    char rand_egd[] = "/tmp/rand-egd-test";
    int z;
    int l = 256;

    SSL_load_error_strings(); 
    SSL_library_init();

    /* Actually should fail */
    z = RAND_egd_bytes(rand_egd,l);

    return 0;
}
EOF
    
    	rpathlist=''
	linklist=''
	if $test "$tls_lib_dir" != "" ; then
	    linklist="-L$tls_lib_dir"
	    rpathlist="$rpath_opt$tls_lib_dir"
	fi

	inclist=''
	if $test "$tls_include_dir" != "" ; then
	    inclist="-I$tls_include_dir"
	fi

	if $cc $ccflags -o tryegd $inclist $linklist $rpathlist tryegd.c -lssl -lcrypto > tryegd.log 2>&1
	then
	    $echo $n "compilation succeed... $c"

	    if ./tryegd ; then
		echo "have RAND_egd_bytes()"
		tls_have_egd="$define";
	    else
		echo "calling failed?"
		tls_have_egd="$undef"
	    fi
	else
	    echo "failed compile and link"
	    tls_have_egd="$undef"
	    # cat tryegd.log
	fi
	
	rm -f tryegd.log tryegd.c tryegd

    $cat >trymethod.c <<'EOF'
#include <stdio.h>

#if defined(__STDC__)
#include <stdlib.h>

int main (int argc, char * argv[]);
#else

#ifndef const
#define const
#endif
#endif

#include <openssl/ssl.h>

int main(argc,argv)
    int argc;
    char **argv;
{

    const SSL_METHOD * method =  TESTMETHOD();

    SSL_load_error_strings(); 
    SSL_library_init();

    if (method)
	 return 0;	

    return 1;
}
EOF

    oldallow="$tls_allow_deprecated"
    tls_allow_deprecated=''	
    
    for m in SSLv23 TLS TLSv1 TLSv1_1 TLSv1_2 ; do

	method=${m}_client_method
	outfile=try${m}
	logfile=try${m}.log

	result="$undef";
	
	$echo $n "Testing linking of $method() ... $c"

	if $cc $ccflags -o $outfile $inclist $linklist $rpathlist -DTESTMETHOD=$method trymethod.c -lssl -lcrypto > $logfile 2>&1
	then
	    $echo $n "compilation succeed... $c"
	    
	    if ./$outfile ; then
		echo "have $method()"

		if $grep "is deprecated" $logfile
		then
		    dflt=d
		    case "$oldallow" in
			*/$m/*)
			    dflt=a
			    ;;
		    esac

		    cat <<EOF

Do you want allow or disable deprecated method $method() ? 
Give "a" to allow  method $method() or give "d" to disable  method $method().

EOF
		    rp="a)llow or d)isable  deprecated method $method() ? [$dflt]"

		    res=''
		    
		    while $test "$res" = "" ; do
		    	  echo $n "$rp $c"
    			  . myread		  

    			  case "$ans" in	  
			       allow|a)
			       	  result="$define"
				  echo "deprecated method $method() is allowed"
				  tls_allow_deprecated="$tls_allow_deprecated/$m/"
				  res=allow
				  ;;
			       disable|d)
			       	  result="$undef"
				  echo "deprecated method $method() is disabled"
				  res="disable"
				  ;;
			       *)
				  echo "Use \"a\" to allow $method() or use \"d\" to disable $method()"
				  ;;
			  esac
		    done	
		    
		else
		    result="$define"
		fi
				
	    else
		echo "calling failed?"
		result="$undef"
	    fi
	else
	     echo "failed compile and link"
	     result="$undef"
	     # cat $logfile
	fi

	rm -f $outfile $logfile

	echo "tls_have_${m}='$result'" >> "$build_dir/$mydir/testresult"
    done


    rm -f trymethod.c

else
    cat <<EOF > "$build_dir/$mydir/testresult"
tls_have_SSLv23='$undef
tls_have_TLS='$undef'
tls_have_TLSv1='$undef'
tls_have_TLSv1_1='$undef'
tls_have_TLSv1_2='$undef'
EOF
    
    tls_allow_deprecated='' 
fi

    $cat >X509_test.c <<'EOF'
#include <stdio.h>

#if defined(__STDC__)
#include <stdlib.h>

int main (int argc, char * argv[]);
#endif

#include <openssl/x509v3.h>
#include <openssl/x509.h>
#include <openssl/pem.h>

int main(argc,argv)
    int argc;
    char **argv;
{
	  FILE * f = NULL;
  X509 * cert = NULL;
  int r;
  char * peername = NULL;
  
  if (argc < 3 || ! argv || ! argv[1] || !argv[2]) {
    fprintf(stderr,"Requires <file> and <name> as argument\n");
    return 5;
  }
  
  f = fopen(argv[1],"r");
  if (!f) {
    fprintf(stderr,"Failed to open %s\n",argv[1]);
    return 5;
  }

  cert = PEM_read_X509(f,NULL,NULL,NULL);
  if (!cert) {
    fprintf(stderr,"Failed to parse certificate %s\n",
	    argv[1]);
    return 5;
  }
  
  r = X509_check_host(cert,argv[2],0,0,&peername);

  switch (r) {
  case 1:
    printf ("Certificate %s matches to %s",
	    argv[1],argv[2]);

    if (peername) {
      printf(", peername=%s",peername);
    }
    putchar('\n');
    
    return 0;
  case 0:
    printf ("Certificate %s no not match to %s",
	    argv[1],argv[2]);
    if (peername) {
      printf(", peername=%s",peername);
    }
    putchar('\n');

    
    return 1;
    break;
  case -1:
    fprintf(stderr,"Failed to check certificate %s for %s",
	    argv[1],argv[2]);
    return 2;
  case -2:
    fprintf(stderr,"Failed to check certificate %s for %s - malformed input\n",
	    argv[1],argv[2]);
    return 2;
  }
    
  return 127;

}
EOF

    openssl=`loc openssl openssl $pth`
    case "$openssl" in
	openssl)
	    echo "openssl command not found.  I hope it's in everyone's PATH."
	    ;;
	*)
	    echo "openssl command found from $openssl"
	    ;;
    esac
    
    $echo $n "Testing linking of X509_check_host() ... $c"

    if  $cc $ccflags -o X509_test  $inclist $linklist $rpathlist X509_test.c  -lcrypto >  X509_test.log 2>&1
    then
	$echo "compilation succeed"
	
	echo "Building test certificate ..."

	# This really does not check Subject Alternative Names, however
	
	if openssl req -x509 -new -keyout secret.key -out certificate.crt -subj '/CN=example.com' -nodes;
	then

	    echo "Testing X509_check_host() ..."

	    if ./X509_test certificate.crt example.com;
	    then
		echo "X509_check_host() seems work"
		tls_check_host="$define"
	    else
		echo "Failed to test X509_check_host()"
		tls_check_host="$undef"
	    fi
	    
	else
	    echo "Cerifificate genaration failed -- assuming that  X509_check_host() works"
	    tls_check_host="$define"
	fi


    else  
	echo "failed compile and link"
	tls_check_host="$undef"
	cat  X509_test.log
    fi
    
    rm -f X509_test.log  X509_test   X509_test.c secret.key certificate.crt

    
    . "$build_dir/$mydir/testresult"

    
$spitshell <<EOT > "$build_dir/$mydir/config.res"
#  Support for TLS
tls_ok='$tls_ok'
tls_dir='$tls_dir'
tls_include_dir='$tls_include_dir'
tls_lib_dir='$tls_lib_dir'
tls_have_egd='$tls_have_egd'
tls_allow_deprecated='$tls_allow_deprecated'
tls_check_host='$tls_check_host'
EOT
cat "$build_dir/$mydir/testresult" >> "$build_dir/$mydir/config.res"

rm -r "$build_dir/$mydir/testresult"
