#!/bin/sh

# $Id: saml2setup,v 1.23 2006/04/26 17:38:08 qcheng Exp $
# Copyright  2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
# California 95054, U.S.A. All rights reserved.
# 
# THIS PRODUCT CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF SUN
# MICROSYSTEMS, INC. USE, DISCLOSURE OR REPRODUCTION IS PROHIBITED WITHOUT THE
# PRIOR EXPRESS WRITTEN PERMISSION OF SUN MICROSYSTEMS, INC.
# 
# U.S. Government Rights - Commercial software.
# Government users are subject to the Sun Microsystems, Inc. standard licenses
# agreement and applicable provisions of the FAR and its supplements.
# 
# Use is subject to license terms. Sun, Sun Microsystems, the Sun logo, Java,
# the 100% Pure Java logo and the Solaris logo are trademarks or registered
# trademarks of Sun Microsystems, Inc. in the U.S. and other countries.
# 
# All SPARC trademarks are used under license and are trademarks or registered
# trademarks of SPARC International, Inc. in the U.S. and other countries.
# Products bearing SPARC trademarks are based upon architecture developed by Sun
# Microsystems, Inc.
# 
# UNIX is a registered trademark in the U.S. and other countries, exclusively
# licensed through X/Open Company, Ltd.
# 
# The OPEN LOOK and Sun(TM) Graphical User Interface was developed by Sun
# Microsystems, Inc. for its users and licensees. Sun acknowledges the
# pioneering efforts of Xerox in researching and developing the concept of
# visual or graphical user interfaces for the computer industry. Sun holds a
# non-exclusive license from Xerox to the Xerox Graphical User Interface, which
# license also covers Sun's licensees who implement OPEN LOOK GUIs and otherwise
# comply with Sun's written license agreements.
# 
# This product is covered and controlled by U.S. Export Control laws and may be
# subject to the export or import laws in other countries. Nuclear, missile,
# chemical biological weapons or nuclear maritime end uses or end users, whether
# direct or indirect, are strictly prohibited. Export or reexport to countries
# subject to U.S. embargo or to entities identified on U.S. export exclusion
# lists, including, but not limited to, the denied persons and specially
# designated nationals lists is strictly prohibited.
# 
# Copyright  2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
# California 95054, Etats-Unis. Tous droits rservs.
# 
# CE PRODUIT CONTIENT DES INFORMATIONS CONFIDENTIELLES ET DES SECRETS COMMERCIAUX
# DE SUN MICROSYSTEMS, INC. SON UTILISATION, SA DIVULGATION ET SA REPRODUCTION
# SONT INTERDITES SANS L AUTORISATION EXPRESSE, ECRITE ET PREALABLE DE SUN
# MICROSYSTEMS, INC.
# 
# L'utilisation est soumise aux termes de la Licence.
# 
# Sun, Sun Microsystems, le logo Sun, Java, le logo 100% Pure Java et le logo
# Solaris sont des marques de fabrique ou des marques dposes de Sun
# Microsystems, Inc. aux Etats-Unis et dans d'autres pays.
# 
# Toutes les marques SPARC sont utilises sous licence et sont des marques de
# fabrique ou des marques dposes de SPARC International, Inc. aux Etats-Unis
# et dans d'autres pays. Les produits portant les marques SPARC sont bass sur
# une architecture dveloppe par Sun Microsystems, Inc.
# 
# UNIX est une marque dpose aux Etats-Unis et dans d'autres pays et licencie
# exlusivement par X/Open Company, Ltd.
# 
# L'interface d'utilisation graphique OPEN LOOK et Sun(TM) a t dveloppe par
# Sun Microsystems, Inc. pour ses utilisateurs et licencis. Sun reconnat les
# efforts de pionniers de Xerox pour la recherche et le dveloppement du concept
# des interfaces d'utilisation visuelle ou graphique pour l'industrie de
# l'informatique. Sun dtient une license non exclusive de Xerox sur l'interface
# d'utilisation graphique Xerox, cette licence couvrant galement les licencis
# de Sun qui mettent en place l'interface d'utilisation graphique OPEN LOOK et
# qui, en outre, se conforment aux licences crites de Sun.
# 
# Ce produit est soumis  la lgislation amricaine en matire de contrle des
# exportations et peut tre soumis  la rglementation en vigueur dans d'autres
# pays dans le domaine des exportations et importations. Les utilisations, ou
# utilisateurs finaux, pour des armes nuclaires,des missiles, des armes
# biologiques et chimiques ou du nuclaire maritime, directement ou
# indirectement, sont strictement interdites. Les exportations ou rexportations
# vers les pays sous embargo amricain, ou vers des entits figurant sur les
# listes d'exclusion d'exportation amricaines, y compris, mais de manire non
# exhaustive, la liste de personnes qui font objet d'un ordre de ne pas
# participer, d'une faon directe ou indirecte, aux exportations des produits
# ou des services qui sont rgis par la lgislation amricaine en matire de
# contrle des exportations et la liste de ressortissants spcifiquement
# dsigns, sont rigoureusement interdites.
# 

verbose=1

AWK=/usr/bin/awk
OS=`/bin/uname -s`
ECHO=/bin/echo

if [ "$OS" = "SunOS" ]; then
    NAWK=/usr/bin/nawk
    AFILE=/tmp/pkg.admin
    RFILE=/tmp/pkg.resp
    OMIT="\c"
    NECHO=$ECHO
else
    OMIT=""
    NECHO="$ECHO -n"
    NAWK=/usr/bin/awk
fi

pdir=`dirname $0`

SILENT_FILE=
INSTALL_OPTION=

# default install level is level2, generate the war file for the user
INSTALL_LEVEL=2

displayMessage()
{
    msg=$1
    if [ $verbose = 1 ]; then
        $ECHO "$msg"
    fi
    $ECHO "$msg" >>$saml2_log
}

displayUsage() {
echo ""
echo "USAGE"
echo "    saml2setup install -s <silent> [-p]"
echo "    saml2setup uninstall -s <silent>"
echo "    saml2setup configure -s <silent>"
echo "    saml2setup unconfigure -s <silent>"
echo "    saml2setup update -s <silent>"
echo "    saml2setup -?"
echo ""
echo "DESCRIPTION"
echo "    saml2setup creates WAR file for AM/FM"
echo "    By default, saml2setup performs the following operation:"
echo "        - it install/configure the new SAML v2 plugin setting on the"
echo "          existing AM/FM."
echo "        - it generate new WAR file for redeployment."
echo ""
echo "    install,  install and configure SAML v2 plugin on AM/FM"
echo ""
echo "    uninstall, uninstall and unconfigure SAML v2 plugin on AM/FM"
echo ""
echo "    configure,  configure SAML v2 plugin on AM/FM"
echo ""
echo "    unconfigure,  unconfigure SAML v2 plugin on AM/FM"
echo ""
echo "    update,  update configured staging directory with files from package "
echo "             directory and regenerate WAR. This option is used after"
echo "             installing SAML v2 plugin patches."
echo ""
echo "    -s <file name>, --silent <file name>"
echo "        Name of the silent install file which contains installation"
echo "        parameters."
echo ""
echo "OPTIONS"
echo ""
echo "    -v   display version information"
echo ""
echo "    -p   install SAML v2 package only"
echo ""
echo "    -?, --help"
echo "        Display help information."
echo ""
}

parseInput()
{
    # by default, mode=0 which will perform all three tasks
    mode=1
    while [ "$1" != "" ]; do
	if [ "$1" = "-p" ]; then
		INSTALL_LEVEL=1
		shift
        elif [ "$1" = "install" ]; then
               INSTALL_OPTION="install"
               shift
        elif [ "$1" = "uninstall" ]; then
               INSTALL_OPTION="uninstall"
	       INSTALL_LEVEL=4
               shift
        elif [ "$1" = "configure" ]; then
               INSTALL_OPTION="configure"
               shift
        elif [ "$1" = "unconfigure" ]; then
		INSTALL_OPTION="unconfigure"
		INSTALL_LEVEL=3
               shift
        elif [ "$1" = "update" ]; then
		INSTALL_OPTION="update"
		shift
        # get the silent file option
        elif [ "$1" = "-s" ] || [ "$1" = "--silent" ]; then
            if [ "$2" = "" ]; then
               displayUsage
	       exit 1
            else
               SILENT_FILE=$2
               shift
               shift
            fi
        # get the help option
        elif [ "$1" = "-?" ] || [ "$1" = "--help" ]; then
            displayUsage
            exit 0
        # get the help option for everything else
	elif [ "$1" = "-v" ]; then
	    if [ -f $pdir/version ]; then
		cat $pdir/version
	    else
		cat $pdir/../lib/version
	    fi
	    exit 0
        else
            displayUsage
            exit 1
        fi
    done

    # check the mandatory options
    if [ "$INSTALL_OPTION" = "" ] || [ "$SILENT_FILE" = "" ]; then
        displayUsage
        exit 1
    fi
}

validateUser()
{
    if test `id | $AWK '{print $1}'` != "uid=0(root)"
    then
        eval $ECHO "You must be root user to run saml2install."
        exit 1
    fi
}

saml2pkgadd()
{

displayMessage "Installing SAML2 packages ..."

if [ x"$BASEDIR" = "x" ];then
        BASEDIR=/opt
        export BASEDIR
fi

if [ "$OS" = "SunOS" ]; then
# build AFILE for SUNWsaml2
cat <<EOF > $AFILE
#ident  "@(#)default    1.4     92/12/23 SMI"   /* SVr4.0  1.5.2.1      */
mail=
instance=unique
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=${BASEDIR:-/opt}
EOF

cat <<EOF >$RFILE
y
y
y
EOF

pkgadd -n -a $AFILE -d `pwd` -r $RFILE -R / SUNWsaml2 1>>$saml2_log 2>&1
else
rpm -ivh --prefix=$BASEDIR RPMS/i686/sun-saml2-*.rpm
fi
}

# check the system if AM/FM installed
validateSystem()
{
    if [ "$OS" = "SunOS" ]; then
        PRODUCT_DIR="SUNWam"
	if [ "$IDPDISCOVERY_ONLY" = "true" ]; then
	    BASEDIR="/opt"
            SYSTEM="AM"
	else
            if [ "$SYSTEM" = "AM" ]; then
                pkginfo -q SUNWamsvc
                if [ $? -eq 0 ]; then
                    BASEDIR=`pkginfo -r SUNWamsvc`
                else
                    $ECHO "No Access Manager installed on the system."
                    exit 1
                fi
            elif [ "$SYSTEM" = "FM" ]; then
                pkginfo -q SUNWamfm
                if [ $? -eq 0 ]; then
                    BASEDIR=`pkginfo -r SUNWamfm`
                else
                    $ECHO "No Federation Manager installed on the system."
                    exit 1
                fi
            else
                pkginfo -q SUNWamfm
                if [ $? -eq 0 ]; then
                    SYSTEM="FM"
                    BASEDIR=`pkginfo -r SUNWamfm`
                else
                    pkginfo -q SUNWamsvc
                    if [ $? -eq 0 ]; then
                        BASEDIR=`pkginfo -r SUNWamsvc`
                        SYSTEM="AM"
                    else
                        SYSTEM=""
                    fi
                fi
            fi
	fi
    else
        PRODUCT_DIR="identity"
	if [ "$IDPDISCOVERY_ONLY" = "true" ]; then
	    BASEDIR="/opt/sun"
            SYSTEM="AM"
	else
            if [ "$SYSTEM" = "AM" ]; then
		rpm -q --quiet sun-identity-services
		if [ $? -eq 0 ]; then
		    BASEDIR=`rpm -ql sun-identity-services | grep services.war | sed -e "s#/identity/services.war##"`
                else
                    $ECHO "No Access Manager installed on the system."
                    exit 1
                fi
            elif [ "$SYSTEM" = "FM" ]; then
		rpm -q --quiet sun-identity-fm
		if [ $? -eq 0 ]; then
		    BASEDIR=`rpm -ql sun-identity-fm | grep "/identity/fm/web-src$" | sed -e "s#/identity/fm/web-src##"`
                else
                    $ECHO "No Federation Manager installed on the system."
                    exit 1
                fi
            else
		rpm -q --quiet sun-identity-fm
                if [ $? -eq 0 ]; then
                    BASEDIR=`rpm -ql sun-identity-fm | grep "/identity/fm/web-src$" | sed -e "s#/identity/fm/web-src##"`
                    SYSTEM="FM"
                else
		    rpm -q --quiet sun-identity-services
                    if [ $? -eq 0 ]; then
                        BASEDIR=`rpm -ql sun-identity-services | grep services.war | sed -e "s#/identity/services.war##"`
                        SYSTEM="AM"
                    else
                        SYSTEM=""
                    fi
                fi
            fi
	fi
    fi

    if [ "$SYSTEM" = "" ]; then
        $ECHO "SAML v2 plugin requres AM/FM installed."
        exit 1
    elif [ "$IDPDISCOVERY_ONLY" = "false" ]; then
        $ECHO  "Found $SYSTEM installed on this system."
    fi

}

# Make sure Staging area exists.
validateEnvironment()
{
    if [ "$IDPDISCOVERY_ONLY" != "true" ]; then
	if [ "$STAGING_DIR" = "" ] || [ ! -d $STAGING_DIR ]; then
	    echo "Staging directory $STAGING_DIR does not exist!"
	    exit 2
	fi
    fi
}

validateResponse()
{
    ok="no"

    question=$1
    default=$2

    valids="ynYN"
    while [ "$ok" = "no" ]
    do
        if [ "$default" = "y" ] || [ "$default" = "Y" ]; then
            $ECHO
            $NECHO "$question [y]/n: ${OMIT}"
            default="y"
        elif [ "$default" = "n" ] || [ "$default" = "N" ]; then
            $ECHO
            $NECHO "$question y/[n]: ${OMIT}"
            default="n"
        else
            $ECHO
            $NECHO "$question y/n: ${OMIT}"
            default=""
        fi
        read ans

        if [ "$ans" = "" ]; then
            if [ "$default" != "" ]; then
                ans=$default
            fi
        fi

        if [ "$ans" = "y" ] || [ "$ans" = "Y" ] || [ "$ans" = "N" ] || [ "$ans" = "n" ]; then
            ok="yes"
        fi

        if [ "$ok" = "no" ]; then
            $ECHO
            $ECHO "Invalid response!"
            $ECHO
        fi
    done

    # make sure we have a std response so client doesn't need to check
    if [ "$ans" = "Y" ]; then
        ans="y"
    elif [ "$ans" = "N" ]; then
        ans="n"
    fi
}

################################################################
#
# main start
# this program will support the default .war generation +
# - cleanup system
# - configure AM/FM + .war gen + deploy
#

validateUser

parseInput $*

if [ "$INSTALL_OPTION" = "install" ] || [ "$INSTALL_OPTION" = "configure" ]; then
    if [ -f $pdir/LICENSE.TXT ];then
	more $pdir/LICENSE.TXT
	validateResponse "Do you agree to the license terms?" "n"
	if [ "$ans" = "y" ]; then
	    $ECHO ""
	else
	    exit 0
	fi
    fi
fi

$ECHO ""

if [ "$saml2_log" = "" ]; then
  saml2_log=/tmp/`basename $0`.log.$$
  export saml2_log
  $ECHO ""
  $ECHO "Logging messages to $saml2_log"
fi

touch $saml2_log

if [ ! -f $SILENT_FILE ];then
    $ECHO "The silent install file, $SILENT_FILE, could not be found."    
    exit 0
else
    # import silentfile
    . $SILENT_FILE
fi

validateSystem

validateEnvironment

# installed SAMLv2 package
if [ "$OS" = "SunOS" ]; then
    pkginfo -q SUNWsaml2
    if [ $? -ne 0 ]; then
	if [ "$INSTALL_OPTION" = "install" ]; then
	   saml2pkgadd
	else
	   $ECHO "No SAML2 pacakge installed."
	   exit 1
	fi
    fi
else
    rpm -q --quiet sun-saml2
    if [ $? -ne 0 ]; then
	if [ "$INSTALL_OPTION" = "install" ]; then
	    saml2pkgadd
	else
	    $ECHO "No SAML2 pacakge installed."
	    exit 1
	fi
    fi
fi

if [ $INSTALL_LEVEL = 1 ]; then
	$ECHO "SAML2 package has been installed!!!"
	exit 0
fi

. $BASEDIR/$PRODUCT_DIR/saml2/lib/saml2util

displayMessage ""

#
# from here down is all install related
#

if [ "$IDPDISCOVERY_ONLY" = "false" ]; then
   getSystemFiles
fi

if [ "$INSTALL_OPTION" = "uninstall" ];then
    if [ "$OS" = "SunOS" ]; then
	pkginfo -q SUNWsaml2 
	if [ $? -eq 0 ]; then
	    RestoreFiles
            cleanUpAll
            displayToDoMessage
            exit 0
	else
            displayToDoMessage "SAML v2 plugin is not installed on the system."
            exit 1
	fi
    else
	rpm -q --quiet sun-saml2
	if [ $? -eq 0 ]; then
	    RestoreFiles
	    cleanUpAll
	    displayToDoMessage
	    exit 0
	else
	    displayToDoMessage "SAML v2 plugin is not installed on the system."
	    exit 1
	fi

    fi
elif [ "$INSTALL_OPTION" = "install" ];then
    if [ "$IDPDISCOVERY_ONLY" = "false" ]; then
	configureSAML2
    fi
    configureIDPDiscovery
elif [ "$INSTALL_OPTION" = "configure" ];then
    if [ "$IDPDISCOVERY_ONLY" = "false" ]; then
	configureSAML2
    fi
    configureIDPDiscovery
elif [ "$INSTALL_OPTION" = "update" ];then
    if [ "$IDPDISCOVERY_ONLY" = "false" ]; then
	updateSAML2
    fi
    configureIDPDiscovery
elif [ "$INSTALL_OPTION" = "unconfigure" ];then
    RestoreFiles
fi


displayMessage ""
displayToDoMessage
