#!/bin/sh
#
#     Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
#     Use is subject to license terms.
#

#
# Common methods
#
printUsage()
{
    echo "Usage:"
    # starts the UI console (runs GUI or, if "-m autoreg" also given, autoreg).
    # Note. "-m autoreg" is undocumented; should only be invoked by Solaris SMF.
    echo "  sconadm register -c"
    # starts the CLI (command line interface).
    echo "  sconadm register -a -r <registration profile>"
    echo "                   [-u <user name>]"
    echo "                   [-h <host name>]"
    echo "                   [-e <softwareUpdate>]"
    echo "                   [-E <softwareUpdate>]"
    echo "                   [-N ]"
    echo "                   [-p <proxy host>[:<proxy port>]]"
    echo "                   [-x <proxy user>]"
    echo "                   [-l <location of log file>]"
    # sets the proxy parameters for all the components.
    # Mainly used to set proxy user name and password by superuser.
    echo "  sconadm proxy    -r <registration profile>"
    echo "                   [-p <proxy host>[:<proxy port>]]"
    echo "                   [-x <proxy user>]"
    echo "                   [-l <location of log file>]"

    # return 1. If we are here, it is because of an error.
    return 1;
}

printTOUMessage()
{
    echo "You must accept terms of use (by passing in -a) in order to register"
    echo "the system. The terms of use and binary code license agreement are"
    echo "located at:"
    echo
    echo "Terms of Use: http://sun.com/applink/sunuc/tou1en"
    echo "Binary Code License Agreement: http://sun.com/applink/sunuc/bcl1en"

    return 0;
}

# Check whether the autoreg profile existed
hasNoAutoregFile()
{
    notEXISTED=0;
    AUTO_REG_FILE=/usr/lib/breg/data/autoRegistrationProfile.xml

    if [ -r ${AUTO_REG_FILE} ]; then	
	notEXISTED=1;
    fi

    return ${notEXISTED};
}

# Check whether the system has registered
hasRegistered()
{
    REGISTERED=1;
    CHECKER=/usr/lib/sam/lib/checkreg    
    RESULT=`${CHECKER}`

    if [ "${RESULT}" = "1" ]; then
	REGISTERED=0;
    fi

    return ${REGISTERED};
}

# CR 6301693 - MV
isFirstRebootInCDInstall()
{
    WORK_DIR=/var/sadm/launcher
    if [ -d "${WORK_DIR}/.autoreboot" ]; then
        return 1
    else
        return 0
    fi
    return 0
}

# Check if current user is an admin user (viz root at this time).
isAdminUser()
{
    # do not use XCU4 binary, use /usr/bin/id instead. XCU4 is not
    # present in the Base OS installation profile.
    _ID=`/usr/bin/id`
    _UID=`/usr/bin/expr "${_ID}" : 'uid=\([^(]*\)'`
    if [ "${_UID}" = "0" ]; then
        return 0
    else
        return 1
    fi
}
 
isGlobalZone()
{
     zone=`/usr/sbin/zoneadm list -p | awk 'BEGIN {FS=":"} {if(NR==1) print $1}`
     if [ "${zone}" = "0" ]; then
     	return 0
     else
	return 1
     fi
}

# create Update Manager start up flag file for auto-reg
markUMFlag()
{
    CCR=/usr/lib/cc-ccr/bin/ccr
    # check whether it is auto-register. If that is the case,
    # create a flag file which will be used to start UM by
    # the script(/usr/dt/config/Xsession.d/1099.br). 
    if "${AUTOREG}" && hasRegistered; then
	$CCR -p "cns.swup.UMautolaunch" -v "true"
    fi
}

runRegisterUI()
{
    # register subcommand
    java -client -jar ${MAIN_JAR} $*
    markUMFlag
}

runRegisterCLI()
{
    # register subcommand
    exec java -classpath ${MAIN_JAR} com.sun.cns.basicreg.BasicRegCLI register $*
}

runProxyCLI()
{
    # proxy subcommand
    exec java -classpath ${MAIN_JAR} com.sun.cns.basicreg.BasicRegCLI proxy $*
}

runCacaoCommand()
{
    if [ "$1" = "start" ]; then
        # First call scn base to start
        /usr/lib/scn/bin/init-scn-base
        # deploy modules if any.
    fi

    if [ "$1" = "stop" ]; then
        # dont have a finish-scn-base yet.
        /usr/sbin/cacaoadm stop
    fi
}

###########################################################################
# Main
###########################################################################
# Constants
LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:/usr/sfw/lib"
LD_LIBRARY_PATH="/usr/lib/sam/lib:/usr/lib/dc:/usr/lib/breg:${LD_LIBRARY_PATH}"
export LD_LIBRARY_PATH
MAIN_JAR="/usr/lib/breg/basicreg.jar"
ACCEPT_TOU_BCL="false"
LOG_LOCATION="/tmp"
START_UI="false"
AWK_EXEC=/usr/bin/awk
LS_EXEC=/usr/bin/ls
FILE_PERMISSION_400="-r--------"
FILE_PERMISSION_600="-rw-------"
REGISTRATION_PROFILE_TEMPLATE="/usr/lib/breg/data/RegistrationProfile.properties"
NEVER_REGISTER="false"
AUTOREG="false"

# Check for zone
isGlobalZone
if [ $? -ne 0 ]; then
    echo "BR will only run in global zone. Exiting..."
    exit 0 ;
fi

# Check for root user privileges.
isAdminUser 
if [ $? -ne 0 ]; then
:
#    echo "Only root can run this command. Exiting..."
#    exit 1
fi

# check if this is a reboot after a first CD installation.
# CR 6301693
isFirstRebootInCDInstall
if [ $? -eq 1 ]; then
    echo "The folder /var/sadm/launcher/.autoreboot is present."
    echo "It is likely that an OS installation is in progress."
    echo "Exiting..."
    exit 0
fi

# check for subcommands. 
# if not proxy or register, print usage and get out.
case "$1" in
*register*|*REGISTER*)
    SUBCOMMAND=register
    ;;
*proxy*|*PROXY*)
    SUBCOMMAND=proxy
    ;;
*cacao*|*CACAO*)
    SUBCOMMAND=cacao
    ;;
*)
    SUBCOMMAND=""
    printUsage
    exit 1;
esac

# Shift left and process the subcommand arguments.
shift

# process register subcommand and args.
if [ "${SUBCOMMAND}" = "register" ]; then
    # save the register subcommand arguments.
    REGISTER_ARGUMENTS=$*
    while getopts car:u:h:e:E:p:x:l:N  __opt
    do
        case $__opt in
        c) START_UI="true"
           shift
           REGISTER_ARGUMENTS=$*
	   if echo ${REGISTER_ARGUMENTS} \
	       | grep "\-m autoreg">/dev/null > /dev/null; then
	       AUTOREG="true"
	   fi
	   ;;
        a) ACCEPT_TOU_BCL="true"
           ;;
        r) REGISTRATION_PROFILE=$OPTARG
           ;;
        u|h|e|E|p|x)
           # simply pass these as-is.
           ;;
        l) LOG_LOCATION=$OPTARG
           ;;
        N) NEVER_REGISTER="true"
           REGISTRATION_PROFILE=$REGISTRATION_PROFILE_TEMPLATE
           ;; 
        \?) 
           printUsage
           exit 1
           ;;
        esac
    done
   
    if "${AUTOREG}"; then
	#check whether the auto-registration file existed
	if hasNoAutoregFile; then
            echo "Don't need auto-registration."
            exit 0
        fi

	if hasRegistered; then
	    echo "System has already been registered,quit auto-registration"
            exit 0
        fi
    fi

    # validate the register subcommand args.
    if [ "${START_UI}" = "true" ]; then
        # start the register UI
        runRegisterUI ${REGISTER_ARGUMENTS}
    else
        if [ "${NEVER_REGISTER}" = "false" -a "${ACCEPT_TOU_BCL}" = "false" ]; then
            # tryin to register without accepting license.
            printTOUMessage
            exit 2;
        fi

        if [ -z "${REGISTRATION_PROFILE}" -o ! -r "${REGISTRATION_PROFILE}" ]; then
            # if profile not defined or not readable, exit.
            echo "Registration profile file \"${REGISTRATION_PROFILE}\" must exist and must be readable."
            exit 3;
        fi

        if [ ! -d "${LOG_LOCATION}" ]; then 
            echo "Log file location \""${LOG_LOCATION}"\" must exist."
            exit 3; 
        fi
        
	OWNERSHIP="`$LS_EXEC -l $REGISTRATION_PROFILE | $AWK_EXEC '{print $3}'`"
	if [ ${OWNERSHIP} != "root" ]; then
	    echo "The ownership of ${REGISTRATION_PROFILE} must be root"
	    exit 1;
	fi

	FILE_PERMISSION="`$LS_EXEC -l $REGISTRATION_PROFILE | $AWK_EXEC '{print $1}'`"
	if [ ${FILE_PERMISSION} != ${FILE_PERMISSION_400} -a ${FILE_PERMISSION} != ${FILE_PERMISSION_600} ]; then
	    echo "The file permission of ${REGISTRATION_PROFILE} must be either 400 or 600"
	    exit 1;
	fi

        # start the register CLI.
        runRegisterCLI ${REGISTER_ARGUMENTS}
    fi
fi

# process proxy subcommand and its args.
if [ "${SUBCOMMAND}" = "proxy" ]; then
    PROXY_ARGUMENTS=$*
    while getopts r:p:x:l: __opt
    do
        case $__opt in
        r) REGISTRATION_PROFILE=$OPTARG
           ;;
        p|x)
           ;;
        l) LOG_LOCATION=$OPTARG
           ;;
        \?)
           printUsage
           exit 1
           ;;
        esac
    done

    if [ ! -d "${LOG_LOCATION}" ]; then 
        echo "Log file location \""${LOG_LOCATION}"\" must exist."
        exit 3; 
    fi
    runProxyCLI ${PROXY_ARGUMENTS}
fi 

# process the cacao subcommand.
if [ "${SUBCOMMAND}" = "cacao" ]; then
    CACAO_ARGUMENTS=$1;
    runCacaoCommand ${CACAO_ARGUMENTS}
fi

exit 0
