src/cmd/localeadm/localeadm
author jant
Wed, 10 Sep 2008 22:06:12 +0200
changeset 266 3e712924d953
parent 260 ec4a21e49073
child 272 8771da775132
permissions -rwxr-xr-x
CR 6744129: Updating cprint_* functions in localeadm script. Also small update done to Locale_config.S11?.txt files.

#!/usr/bin/ksh
# 
# Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
# 
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
# 
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
# 
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
# 
#
###########################################################################
#####################    programs, files   ################################
###########################################################################
grep=/usr/xpg4/bin/grep
awk=/usr/xpg4/bin/awk
expr=/usr/bin/expr
tee=/usr/bin/tee
gettext=/usr/bin/gettext



#find out Solaris version to set number of CDs
typeset solarisVersion=`uname -r | sed -e "s/5.//"`
#print "Solaris version: $solarisVersion\n"
if [ $solarisVersion = "10" ]
then
  set -A solarisImages solaris1 solaris2 solaris3 solaris4 solaris5
else 
  set -A solarisImages solaris1 solaris2 solaris3 solaris4 solaris5 solaris6
fi
# still have some references to solaris1 image, but that is where the check for CD/DVD is performed

set -A langcdImages langcd1 langcd2
# MP now only function print_system is using langcd names, all others where removed


###########################################################################
###################    print localized messages   #########################
###########################################################################
# 
# $1 - string to print
# $2 - logging level: either "log", "logvb" or "nolog"
# $3 - argument 1 (if string needs it)
# $4 - argument 2 (if string needs it)

loc_prnt()
{

typeset msg=`$gettext --domain=localeadm "$1"`

typeset log=$2 arg1=$3 arg2=$4 

#echo "log is $log"
if [ "$log" = "logvb" ]  #write to log always, user only in verbose mode
then
  if [ "$VERBOSE" = "y" ]
  then
	if [ $# -le 3 ]
	then
	    printf "$msg" "$arg1"| $tee -a $LOGFILE
	    echo | $tee -a $LOGFILE
	else
	    printf "$msg" "$arg1" "$arg2"| $tee -a $LOGFILE
	    echo | $tee -a $LOGFILE
	fi
   else  # no verbose
	if [ $# -le 3 ]
	then
	    printf "$msg" "$arg1" >> $LOGFILE
	    echo >> $LOGFILE
	else
	    printf "$msg" "$arg1" "$arg2" >> $LOGFILE
	    echo >> $LOGFILE
	fi
    fi
elif [ "$log" = "log" ]  # write to log & user always
then
    if [ $# -le 3 ]
    then
	printf "$msg" "$arg1"| $tee -a $LOGFILE
	echo | $tee -a $LOGFILE
    else
	printf "$msg" "$arg1" "$arg2"| $tee -a $LOGFILE
	echo | $tee -a $LOGFILE
    fi
else  # never log, just send to user
    if [ $# -le 3 ]
    then
	printf "$msg" "$arg1"
	echo
    else
	printf "$msg" "$arg1" "$arg2"
	echo
    fi
fi    

}

###########################################################################
########################    print help   ##################################
###########################################################################

print_help() {
    loc_prnt "usage: \nlocaleadm [-lcs] [-q locale|region] [-d device] [-t] [-R root_path]" nolog
    echo "localeadm [-a] [-r] locale|region [-m] [-d solaris_1 | dvd_image] [-t] [-R root_path]"
    echo
    loc_prnt "\t-a  Add the packages for <locale> or <region> to the system" nolog
    loc_prnt "\t-c  Display the locales by codeset name. Use with -l" nolog
    loc_prnt "\t-C  Create a new config file based on the set of images available to you" nolog
    loc_prnt "\t-d  Select the device to add or list locales/regions from" nolog
    loc_prnt "\t-f  Check the pkgs modified by a previous add/remove operation. If there was a failure, this will try to fix the problem." nolog
    loc_prnt "\t-h  Print this help screen" nolog
    loc_prnt "\t-l  List the locales installed on the system or available from a device <device> (if used with -d)" nolog
    loc_prnt "\t-m  Add/remove message support for a locale/region" nolog
    loc_prnt "\t-q  Query to see is <locale> or <region> installed on the system" nolog
    loc_prnt "\t-r  Remove the packages for <locale> or <region> from the system" nolog
    loc_prnt "\t-R  Add, remove, list or query locales/regions installed on root_path" nolog
    loc_prnt "\t-s  Short listing. Only lists region names. Use with -l" nolog
    loc_prnt "\t-t  Test mode. Simulates add or delete, but makes no changes to the system" nolog
    loc_prnt "\t-v  Verbose mode. Gives more detail of operations performed" nolog
    echo 
    echo " e.g. localeadm -l"
    loc_prnt "\t- lists all the regions & locales installed on the system by name" nolog
    echo "  localeadm -lc -d /cdrom/cdrom0"
    loc_prnt "\t- lists all regions available from /cdrom/cdrom0 by codeset" nolog
    echo "  localeadm -a neu -m -d /images/S10"
    loc_prnt "\t- adds the Northern Europe region without message support from /images/S10" nolog
    echo
    loc_prnt "See the localeadm(1M) man page for more details" nolog
    echo 
}

###########################################################################
########  restart fc-cache - refresh fonts cache to be sure that  #########
########  we avoid desktop login problems/crash (e.g. 6495514)    #########
###########################################################################

restart_fccache() {
  typeset sol_version=`uname -r | awk -F. '{print $2}'`
  typeset status=1

  if [ $sol_version -gt 9 ]; then
      svcadm restart svc:/application/font/fc-cache:default
      status=$?
  else
      /usr/bin/fc-cache
      status=$?
  fi

  if [ $status != 0 ]; then
      echo
      loc_prnt "WARNING: There was an error when refreshing fc-cache. Login to GUI desktop may not work as expected." nolog
  fi
  return $status
}

###########################################################################
#############  print the locales available for install  ###################
###########################################################################
#
# $1 - the invalid argument

print_help_msg() {
    echo
    loc_prnt "Invalid argument: %s" nolog $1
    loc_prnt "Please run 'localeadm -h' for a list of valid arguments" nolog 
    echo
    rem_lock
    exit 1
}
    
###########################################################################
#############  print the locales available for install  ###################
###########################################################################

print_aua() {
    echo "$1 (aua)"
    loc_prnt "[ Australia, New Zealand ]" nolog
    echo
}

print_cam() {
#    loc_prnt "$1 (%s)" nolog cam
    echo "$1 (cam)"
    loc_prnt "[ Costa Rica, Guatemala, Nicaragua, Panama, El Salvador ]" nolog
    echo
}

print_ceu() {
#    loc_prnt "$1 (%s)" nolog ceu
    echo "$1 (ceu)"
    loc_prnt "[ Austria, Czech Republic, Germany, Hungary, Poland, Slovakia, Switzerland (German), Switzerland (French) ]" nolog
    echo
}

print_eeu() {
    echo "$1 (eeu)"
    loc_prnt "[ Albania, Bosnia, Bulgaria, Estonia, Croatia, Kazakhstan, Lithuania, Latvia, Macedonia, Romania, Russia, Serbia, Slovenia, Turkey, Ukraine ]" nolog
    echo
}

print_mea() {
    echo "$1 (mea)"
    loc_prnt "[ Saudi Arabia, Israel ]" nolog
    echo
}

print_naf() {
    echo "$1 (naf)"
    loc_prnt "[ Egypt ]" nolog
    echo
}

print_nam() {
    echo "$1 (nam)"
    loc_prnt "[ Canada (English), Canada (French), United States, Mexico ]" nolog
    echo
}

print_neu() {
    echo "$1 (neu)"
    loc_prnt "[ Denmark, Finland, Iceland, Norway (Bokmal), Norway (Nyorsk),  Sweden ]" nolog
    echo
}

print_sam() {
    echo "$1 (sam)"
    loc_prnt "[ Argentina, Bolivia, Brazil, Chile, Colombia, Ecuador, Paraguay, Peru, Uruguay, Venezuela ]" nolog
    echo
}


print_seu() {
    echo "$1 (seu)"
    loc_prnt "[ Cyprus, Italy, Greece, Malta (English), Malta (Maltese), Portugal, Spain (Catalan), Spain (Spanish) ]" nolog
    echo
}

print_weu() {
    echo "$1 (weu)"
    loc_prnt "[France, Holland, Belgium (French), Belgium (Flemish), Ireland, England, Luxembourg (French), Luxembourg (German) ]" nolog
    echo
}

print_sea() {
    echo "$1 (sea)"
    loc_prnt "[ Indonesia, Malaysia, Vietnam ]" nolog
    echo
}

print_taiwan() {
    echo "$1 (taiwan)"
    echo
}

print_hongkong() {
    echo "$1 (hongkong)"
    echo
}

print_china() {
    echo "$1 (china)"
    echo
}

print_ja() {
    echo "$1 (ja)" 
    echo
}

print_korean() {
    echo "$1 (korean)" 
    echo
}

print_th_th() {
    echo "$1 (th_th)" 
    echo
}

print_hi_in() {
    echo "$1 (hi_in)" 
    echo
}


###########################################################################
#############  print the codesets available for install  ##################
###########################################################################

cprint_aua() {
    echo "$1 (aua)" 
    echo "[ en_AU.ISO8859-1, en_AU.UTF-8, en_NZ.ISO8859-1, en_NZ.UTF-8 ]"
    echo
}

cprint_cam() {
    echo "$1 (cam)" 
    echo "[ es_CR.ISO8859-1, es_CR.UTF-8, es_GT.ISO8859-1, es_GT.UTF-8, es_NI.ISO8859-1, es_NI.UTF-8, es_PA.ISO8859-1, es_PA.UTF-8, es_SV.ISO8859-1, es_SV.UTF-8 ]"
    echo
}

cprint_ceu() {
    echo "$1 (ceu)" 
    echo "[ cs_CZ.ISO8859-2, cs_CZ.UTF-8, de_AT.ISO8859-1, de_AT.ISO8859-15, de_AT.UTF-8, de_CH.ISO8859-1, de_CH.UTF-8, de_DE.ISO8859-1, de_DE.ISO8859-15, de_DE.UTF-8, fr_CH.ISO8859-1, fr_CH.UTF-8, hu_HU.ISO8859-2, hu_HU.UTF-8, pl_PL.ISO8859-2, pl_PL.UTF-8, sk_SK.ISO8859-2, sk_SK.UTF-8 ]"
    echo
}

cprint_eeu() {
    echo "$1 (eeu)" 
    echo "[ bg_BG.ISO8859-5, bg_BG.UTF-8, et_EE.ISO8859-15, et_EE.UTF-8, hr_HR.ISO8859-2, hr_HR.UTF-8, lt_LT.ISO8859-13, lt_LT.UTF-8, lv_LV.ISO8859-13, lv_LV.UTF-8, mk_MK.ISO8859-5, mk_MK.UTF-8, ro_RO.ISO8859-2, ro_RO.UTF-8, ru_RU.ISO8859-5, ru_RU.ANSI1251, ru_RU.KOI8-R, ru_RU.UTF-8, sh_BA.ISO8859-2, sh_BA.UTF-8, sl_SI.ISO8859-2, sl_SI.UTF-8, sq_AL.ISO8859-2, sq_AL.UTF-8, sr_YU.ISO8859-5, tr_TR.ISO8859-9, tr_TR.UTF-8, kk_KZ.UTF-8, uk_UA.UTF-8 ]"
    echo
}

cprint_mea() {
    echo "$1 (mea)" 
    echo "[ ar_SA.UTF-8, he, he_IL.UTF-8 ]"
    echo
}

cprint_naf() {
    echo "$1 (naf)" 
    echo "[ ar, ar_EG.UTF-8 ]"
    echo
}

cprint_nam() {
    echo "$1 (nam)" 
    echo "[ en_CA.ISO8859-1, en_CA.ISO8859-15, en_CA.UTF-8, en_US.ISO8859-1, en_US.ISO8859-15, en_US.UTF-8, es_MX.ISO8859-1, es_MX.UTF-8, fr_CA.ISO8859-1, fr_CA.UTF-8 ]"
    echo
}

cprint_neu() {
    echo "$1 (neu)" 
    echo "[ da_DK.ISO8859-1, da_DK.ISO8859-15, da_DK.UTF-8, fi_FI.ISO8859-1, fi_FI.ISO8859-15, fi_FI.UTF-8, is_IS.ISO8859-1, is_IS.UTF-8, no_NO.ISO8859-1@bokmaal, nb_NO.UTF-8, no_NO.ISO8859-1@nyorsk, nn_NO.UTF-8, sv_SE.ISO8859-1, sv_SE.ISO8859-15, sv_SE.UTF-8 ]"
    echo
}

cprint_sam() {
    echo "$1 (sam)" 
    echo "[ es_AR.ISO8859-1, es_AR.UTF-8 , es_BO.ISO8859-1, es_BO.UTF-8 , es_CL.ISO8859-1, es_CL.UTF-8 , es_CO.ISO8859-1, es_CO.UTF-8 , es_EC.ISO8859-1, es_EC.UTF-8 , es_PE.ISO8859-1, es_PE.UTF-8 , es_PY.ISO8859-1, es_PY.UTF-8 , es_UY.ISO8859-1, es_NY.UTF-8 , es_VE.ISO8859-1, es_VE.UTF-8 , pt_BR.ISO8859-1, pt_BR.UTF-8 ]"
    echo
}

cprint_seu() {
    echo "$1 (seu)" 
    echo "[ ca_ES.ISO8859-1, ca_ES.ISO8859-15, ca_ES.UTF-8, el_CY.UTF-8, el_GR.ISO8859-7, el_GR.UTF-8, en_MT.UTF-8, es_ES.ISO8859-1, es_ES.ISO8859-15, es_ES.UTF-8, it_IT.ISO8859-1, it_IT.ISO8859-15, it_IT.UTF-8, mt_MT.UTF-8, pt_PT.ISO8859-1, pt_PT.ISO8859-15, pt_PT.UTF-8 ]"
    echo
}

cprint_weu() {
    echo "$1 (weu)" 
    echo "[de_LU.UTF-8, fr_LU.UTF-8, fr_FR.ISO8859-1, fr_FR.ISO8859-15, fr_FR.UTF-8, fr_BE.ISO8859-1, fr_BE.ISO8859-15, fr_BE.UTF-8, nl_BE.UTF-8, nl_NL.ISO8859-1, nl_NL.ISO8859-15, nl_NL.UTF-8, en_IE.ISO8859-1, en_IE.ISO8859-15, en_IE.UTF-8, en_GB.ISO8859-1, en_GB.ISO8859-15, en_GB.UTF-8] "
    echo
}

cprint_sea() {
    echo "$1 (sea)" 
    echo "[id_ID.UTF-8, ms_MY.UTF-8, vi_VN.UTF-8] "
    echo
}

cprint_taiwan() {
    echo "$1 (taiwan)"
    echo "[ zh_TW, zh_TW.EUC, zh_TW.BIG5, zh_TW.UTF-8 ]" 
    echo
}

cprint_hongkong() {
    echo "$1 (hongkong)"
    echo "[ zh_HK.BIG5HK, zh_HK.UTF-8 ]" 
    echo
}

cprint_china() {
    echo "$1 (china)"
    echo "[ zh_CN.EUC, zh, zh_CN.GB18030, zh_CN.GBK, zh.GBK, zh_CN.UTF-8, zh.UTF-8 ]" 
    echo
}

cprint_ja() {
    echo "$1 (ja)" 
    echo "[ ja, ja_JP.eucJP, ja_JP.EUC, ja_JP.PCK, ja_JP.UTF-8 ]" 
    echo
}

cprint_korean() {
    echo "$1 (korean)" 
    echo "[ ko, ko_KR.EUC, ko.UTF-8, ko_KR.UTF-8 ]" 
    echo
}

cprint_th_th() {
    echo "$1 (th_th)" 
    echo "[ th, th_TH, th_TH.TIS620, th_TH.ISO8859-11, th_TH.UTF-8 ]" 
    echo
}

cprint_hi_in() {
    echo "$1 (hi_in)" 
    echo "[ hi_IN.UTF-8 ]" 
    echo
}

###########################################################################
###############   Selects the region name to print out  ###################
###########################################################################

get_region_name() {

case $1 in
 aua)
    SEL_STR=`$gettext --domain=localeadm "Australasia"`
    ;;
 cam)
    SEL_STR=`$gettext --domain=localeadm "Central America"`
    ;;
 ceu)
    SEL_STR=`$gettext --domain=localeadm "Central Europe"`
    ;;
 eeu)
    SEL_STR=`$gettext --domain=localeadm "Eastern Europe"`
    ;;
 mea)
    SEL_STR=`$gettext --domain=localeadm "Middle East"`
    ;;
 naf)
    SEL_STR=`$gettext --domain=localeadm "Northern Africa"`
    ;;
 nam)
    SEL_STR=`$gettext --domain=localeadm "North America"`
    ;;
 neu)
    SEL_STR=`$gettext --domain=localeadm "Northern Europe"`
    ;;
 sam)
    SEL_STR=`$gettext --domain=localeadm "South America"`
    ;;
 seu)
    SEL_STR=`$gettext --domain=localeadm "Southern Europe"`
    ;;
 weu)
    SEL_STR=`$gettext --domain=localeadm "Western Europe"`    
    ;;
 sea)
    SEL_STR=`$gettext --domain=localeadm "South East Asia"`    
    ;;
 taiwan)
    SEL_STR=`$gettext --domain=localeadm "Traditional Chinese"`
     ;;
 hongkong)
    SEL_STR=`$gettext --domain=localeadm "Traditional Chinese (Hong Kong)"`
    ;;
 china)
  
    SEL_STR=`$gettext --domain=localeadm "Simplified Chinese"`
    ;;
 ja)
    SEL_STR=`$gettext --domain=localeadm "Japanese"`
    ;;
 korean)
    SEL_STR=`$gettext --domain=localeadm "Korean"`
    ;;
 th_th)
    SEL_STR=`$gettext --domain=localeadm "Thai"`
    ;;
 hi_in)
    SEL_STR=`$gettext --domain=localeadm "Hindi"`
    ;;
 *)
    SEL_STR="Locale"
    ;;
esac
if [ "$SEL_STR" = "Locale" ]
then
    return 1 # no correct region found
fi
}

###########################################################################
############  prints the locales currently on the system  #################
###########################################################################
#
# $1 = quiet mode - use for adds/removes if the user hasn't run a listing before. 
# $2 = test mode

print_system(){

typeset -i result=0 keep_list=0 core=0 langcd=0 disks=0

typeset date=`date`

# if we're reading naything that's not physically on / on the machine,
# we want to keep the existing locales.list file.  
if [[ "$ALTROOT" = "y" || "$TEST" = "y"  || "$3" = "all" ]]
then
    typeset -i keep_list=1
fi

# if we have a list and aren't running in test mode, create a backup
if [[ -f $LOCALES_LIST &&  keep_list -ne 1 ]]
then
    cp $LOCALES_LIST $LOCALES_LIST.bak
    rm $LOCALES_LIST
fi

if [ "$1" != "q" ] # check for silent running - no echoes
then
    loc_prnt "Checking for installed packages. This could take a while." nolog
    echo
fi

if [ $keep_list -eq 1 ] # don't want to overwrite the actual list when we're running test mode
then
    cp $LOCALES_LIST $LOCALES_LIST.true
    rm $LOCALES_LIST
fi

#if [[ "$TEST" != "y" || "$3" != "all" ]]
if [ "$3" = "all" ]
then
    loc_prnt "The following regions are available to install from $DEVICE" > $LOCALES_LIST
    echo >> $LOCALES_LIST
elif [ "$TEST" = "n" ]
then
    loc_prnt "The following regions are installed on %s on %s" nolog ${HOST} "${date}" > $LOCALES_LIST
    echo >> $LOCALES_LIST
    echo "POSIX (C)" >> $LOCALES_LIST # we'll always have C locale
    echo >> $LOCALES_LIST
fi

# go through all the regions and check are they on the machine. 
for region in aua cam ceu eeu mea naf nam neu sam seu weu sea ja korean china hongkong taiwan th_th hi_in
do
   # check if there are any packages at all for this region -- this can be important for e.g. new regions
    regionPackages=`$grep $region $CONFIGFILE | $grep -v "locname" | wc -l`
    if [ "$regionPackages" -eq 0 ]
    then
       continue 
    fi

    result=0 # first, reset all vars to 0
    core=0
    langcd=0
    
    get_region_name $region # get the region name we'll be looking for


### Changed the checks on $result to take into acount all the new disks - KC

    if [ "$2" = "y" ] # test mode, don't need to check anything
    then	
	core=2
	result=`expr ${#solarisImages[*]} '*' 2`   # set the result to the total for all disks
	langcd=`expr ${#langcdImages[*]} '*' 2`
    else 
	expectedResult=`expr ${#solarisImages[*]} '*' 2`   # all solaris checks succeedes
	expectedLangcd=`expr ${#langcdImages[*]} '*' 2`    # all langcd check succeedes
	# first, check for core pkgs (minimum locale pkgs)
	if [ "$ALTROOT" = "y" ]
	then
            checkImage="alt"         # check if an alternative root was used
	else
	    if [ "$3" = "all" ]
	    then
               checkImage="disk"     # checking an install dir
	    else
                checkImage="mach"    # checking locales installed on / on the machine
	    fi
	fi
	check_locale $region "$checkImage" "c_solaris" # checking locales installed on / on the machine
	core=`expr $core + $?` # get the result 

	if [ $core -eq 2 ] # if we have at least a core install (missing core pkgs are as good as no locale installed)
	then
	    for disk in  ${solarisImages[*]}   # check each image in turn
	    do
		if [ "$1" = "q" ] # quiet mode
		then
	 	    check_locale $region "$checkImage" "$disk" 2>&1 > /dev/null
		    result=`expr $result + $?`
		else
	            check_locale $region "$checkImage" "$disk" 
		    result=`expr $result + $?`
		fi
	    done
	fi # end "if core=2"
	

	if [ $result -eq $expectedResult  ]  
	then
	    if [ "$1" = "q" ]
		then
		    check_locale $region "$checkImage" "langcd1" 2>&1 > /dev/null
		    langcd=`expr $langcd + $?`
		    check_locale $region "$checkImage" langcd2 2>&1 > /dev/null
		    langcd=`expr $langcd + $?`
		else # end "if quiet mode"
		    check_locale $region "$checkImage" "langcd1"
		    langcd=`expr $langcd + $?`
		    check_locale $region "$checkImage" langcd2
	            langcd=`expr $langcd + $?`
		fi
	fi # end "if result >= 5"
    fi # end if "test mode"

#        print "DEBUG core: $core, result: $result, langcd: $langcd \n"
 # consider locale installed if "allmost All" packages are installed, missing all items from one CD or soem items from 2 CDs
#    if [[ $result -ge $expectedResult && $core -eq 2 && langcd -eq $expectedLangcd ]] # if we have all pkgs incl messages
    if [[ $result -ge $expectedResult && $core -eq 2 ]] 
    then
	case $1 in
	locale)
	    print_$region "${SEL_STR}" >> $LOCALES_LIST
	    ;;
	code)
	    cprint_$region "${SEL_STR}" >> $LOCALES_LIST
	    ;;
	short)
	    echo >> $LOCALES_LIST
	    echo "$SEL_STR ($region)" | $tee -a $LOCALES_LIST
	    echo >> $LOCALES_LIST
	    ;;
	q)
	    echo >> $LOCALES_LIST
	    echo "$SEL_STR ($region)" >> $LOCALES_LIST
	    echo >> $LOCALES_LIST
	    ;;
	esac
#    elif [[ $result -ge $expectedResult && $core -eq 2 ]] # no messages but all solaris_*
#    then
#	### need to translate "(no messages)" - KC
#	nomsg_str=`$gettext --domain=localeadm "(no messages)"`
#
#	case $1 in
#	locale)
#	    print_$region "${SEL_STR} ${nomsg_str}" >> $LOCALES_LIST
#	    ;;
#	code)
#	    cprint_$region "${SEL_STR} ${nomsg_str}" >> $LOCALES_LIST
#	    ;;
#	short)
#	    echo >> $LOCALES_LIST
#	    echo "$SEL_STR ${nomsg_str} ($region)" | $tee -a $LOCALES_LIST
#	    echo >> $LOCALES_LIST
#	    ;;
#	q)
#	    echo >> $LOCALES_LIST
#	    echo "$SEL_STR ${nomsg_str} ($region)" >> $LOCALES_LIST
#	    echo >> $LOCALES_LIST
#	    ;;
#	esac
    # MP this is tricky, this can also mean that core packages are shared - e.g. hongkong and taiwan
    # therefore after removing taiwan those are left on the system and it shows "taiwan incomplete"
    # as a result honkong does not try to remove those packages either, taiwan uses them....
    elif [[ $core -eq 2 ]] # a core install, but nothing else (or missing pkgs)
    then
	### need to translate "(incomplete)" - KC
	incomp_str=`$gettext --domain=localeadm "(incomplete)"`

	case $1 in
	locale)
	    print_$region "${SEL_STR} ${incomp_str}" >> $LOCALES_LIST
	    ;;
	code)
	    cprint_$region "${SEL_STR} ${incomp_str}" >> $LOCALES_LIST
	    ;;
	short)
	    echo >> $LOCALES_LIST
	    echo "$SEL_STR ${incomp_str} ($region)" | $tee -a $LOCALES_LIST
	    echo >> $LOCALES_LIST
	    ;;
	q)
	    echo >> $LOCALES_LIST
	    echo "$SEL_STR ${incomp_str} ($region)" >> $LOCALES_LIST
	    echo >> $LOCALES_LIST
	    ;;
	esac
    fi

done # end "for i in aua....."

echo
echo "-----------------"
echo
cat $LOCALES_LIST

if [ "$1" != "q" ] # check for silent running - no echoes
then	
    loc_prnt "Done." nolog
    if [[ "$TEST" != "y" && $3 != "all" ]]
    then
	loc_prnt "A copy of this report can be found in %s" nolog $LOCALES_LIST
    fi
fi

if [ -f $LOCALES_LIST.true ]
then
    mv $LOCALES_LIST.true $LOCALES_LIST
fi

# the program needs a locales.list file, even if it's empty. So, if there are no 
# locales on the system, we still need the file (should never get here, as C locale
# will always be in the list

if [ ! -f $LOCALES_LIST ]
then
    touch $LOCALES_LIST
fi 
}



#########################################################################################################
###### checks whether the path entred by user points to requestd cd image - check the .volumer.inf file
###### e.g. VI"SOL_10_1008_X86_2"
#########################################################################################################
# params: 
# $1 - the image name langcd1, solaris5... 
#
is_correct_cd() {
        cdName=`echo "$1" | sed -e "s/[0-9]*$//"`
	cdNum=`echo "$1" | sed -e "s/^[a-z]*//"`
        if [ $cdNum -eq 1 ]
	then
		cdNum=""    #the first CD does not have number in .volume.inf
	fi
	# $cdpath is set elsewhere
	#.volume.inf indicates what cd the image is. 		
        if [ "$cdName" = "solaris" ]
        then
		cdcheck=`grep "SOL_[0-9]*_.*"$CDLABEL"_*"$cdNum $cdpath/.volume.inf`
	elif [ "$cdName" = "langcd" ]
	then
		cdcheck=`grep "SOL_[0-9]*.*LANG_"$CDLABEL"_*"$cdNum $cdpath/.volume.inf`
	fi
	
	#if it is not a zero length string, then this is the right cd
	if [ ! -z "$cdcheck" ]
	then
		cdfound=1
	else 
		echo ""
		loc_prnt "%s not found, please insert image %s and enter path: " nolog ${sources[index]} ${sources[index]};
		read cdpath
	fi	
}

###########################################################################
##################   check for an installed locale   ######################
###########################################################################
#
# $1 = region to check (e.g. mea)
# $2 = type to check - a machine (mach), directory (dir) or altroot (alt)
# $3 = disk type to check Locale_config.txt for (i.e. solaris_*, langcd)
# $4 = disk to check (if needed)
#
# returns:
# 0 - no pkgs found
# 1 - some but not all pkgs found
# 2 - all pkgs found

check_locale(){

typeset -l region=$1
typeset -i count=0 pkg_count=0 num=2 
typeset check_disk=$3
typeset disk=$4
 

if [ "$VERBOSE" = "y" ]
then
    loc_prnt "Checking for %s region (%s) (verbose mode)" logvb "$SEL_STR" "$region" 
    loc_prnt "(%s packages)" log $check_disk
else
    loc_prnt "Checking for %s region (%s)" log "$SEL_STR" "$region" 
    loc_prnt "(%s packages)" log $check_disk
fi
    
if [ "$VERBOSE" != "y" ]
then
    print -n "|"
fi

### Moved this check to top to save on processing - KC
# check to see what the pkg_count for this disk *should* be
pkg_count=`$awk '$2 ~ /'$region'/ && $3 ~ /'$check_disk'/ {print $1}' $CONFIGFILE | wc -l`

if [ $pkg_count -eq 0 ] # if there are no pkgs for this region on this disk
then
    return 2 #return "all pkgs found" 
fi

# if we need to look for pkgs......

# find each pkg mentioned in the locales list file where region is $region and the disk is $check_disk
# i.e $awk '$2 ~ /'seu'/ && $3 ~ /'solaris_1'/ {print $1}' (gets all seu pkgs on solaris_1)

for pkg in `$awk '$2 ~ /'$region'/ && $3 ~ /'$check_disk'/ {print $1}' $CONFIGFILE`
do
    if [ "$2" = "mach" ] # if we're checking a machine for installed locales
    then
	pkginfo -q $pkg
    elif [ "$2" = "alt" ]
    then
	pkginfo -R $ALT_ROOT_DIR -q $pkg # read for a pkg installed on $ALT_DIR
    elif [ "$2" = "dir" ] # if we're checking a dir for the pkgs for a locale
    then
	if [ -f $disk/.order ] # if we have a solaris_1 or DVD we don't need to check individual pkgs
	then
	    $grep -q $pkg $disk/.order
	else #we have to do it the slow way
	    find $disk -type d -name $pkg -prune > /dev/null # all we want is the return value
	fi
    fi
    if [ $? -eq 0 ] # if the pkgs is found, up the pkg count
    then
	count=`expr $count + 1`
	if [ "$VERBOSE" = "y" ]
	then
	    loc_prnt "package %s found" logvb $pkg
	else
	    print -n "."
	fi
    else  
	if [ "$VERBOSE" = "y" ]
	then
	    loc_prnt "package %s not found" logvb $pkg
	else
	    print -n "."   
	fi
    fi
done

#loc_prnt 
if [ "$VERBOSE" != "y" ]
then
    print -n "|"
fi
echo
echo

if [ $count -eq $pkg_count ]
then
    loc_prnt "All packages found." nolog
    echo
    return 2 # we have all of the packages
elif [ $count -gt 0 ]
then
    loc_prnt "Not all packages found (%s out of %s)." log $count $pkg_count
    echo
    return 1 #we have some packages, but not all of them
else
    loc_prnt "No packages found." nolog
    echo
    return 0 # we don't have any packages
fi
}

###########################################################################
###############   check for a locale or a region   ########################
###########################################################################
#
# $1 - locale name
# $2 - what type of operation we're doing - install, remove, check or fix

check_region() {

typeset -l locale
locale=${1%%.*} # strip off the ".iso8859" etc, just want aa_BB (e.g. de_DE.ISO8859-1, we just want "de_DE")


if [ "$locale" = "ar" ] # arabic is always a special case
then
    locale="ar_eg"
fi

# find out if it's a unique locale name (partials give problems e.g es_AR vs. es_ES)
# e.g. this line will return 1 for "es_ES", but about 9 for "es", so "es" isn't valid (you can't
# figure out which of the 9 spanish locales you want)
typeset -i loc_count=`$grep locname $CONFIGFILE | sed -e 's/locname//g' | $grep -i " $locale" | wc -l` # MP the grep should not be -i for "ar would match bot h ar_EG and es_AR and possibly others, es_SV and sv_SE

if [ $loc_count -ne 1 ]
then
    loc_prnt "Warning! The name you have given (\"%s\") is not a unique locale or region identifier. Please choose another locale name and try again. " nolog $locale
    echo
    rem_lock
    exit 1
fi

echo

loc_prnt "locale/region name is %s" log $locale

get_region_name $locale

if [ "$SEL_STR" = "Locale" ] # a locale name was entered not a region name
then
    # MP is this if really necessary??? the grep -awk seems to work for all locales
    if [ "$locale" = "ar_eg" ] 
    then
	SEL_REGION="naf"
    elif [ "$locale" = "he" ]
    then
	SEL_REGION="mea"
    else
	# get the region name - find the "locname" line, strip off "locname" (so it doesn't get a match with nam region),
	# print out the 2nd field on the line
	SEL_REGION=`$grep locname $CONFIGFILE | sed -e 's/locname//g' | $grep -i " $locale" | $awk '{print $2}'`
    fi


    get_region_name $SEL_REGION
    echo
    if [ "$2" = "install" ]
    then
	loc_prnt "Warning! You have chosen the %s locale rather than a region to install." nolog "$1" 
	loc_prnt "This locale is part of the %s region. If you choose to continue, all of the locales in this region will be installed." nolog  "$SEL_STR"
    elif [ "$2" = "uninstall" ]
    then 
	loc_prnt "Warning! You have chosen the %s locale rather than a region to remove." nolog "$1" 
	loc_prnt "This locale is part of the %s region. If you choose to continue, all of the locales in this region will be removed."  nolog "$SEL_STR"
    elif [ "$2" = "check" ]
    then
	loc_prnt "Warning! You have chosen the %s locale rather than a region to check." nolog "$1" 
	loc_prnt "This locale is part of the %s region. If you choose to continue, this region will be checked."  nolog "$SEL_STR"
    
    elif [ "$2" = "fix" ]
    then
	loc_prnt "Warning! You have chosen the %s locale rather than a region to fix." nolog "$1" 
	loc_prnt "This locale is part of the %s region. If you choose to continue, this region will be fixed."  nolog "$SEL_STR"
    fi
    
    echo 
    typeset -l ans
    # using gettext rather than a call to loc_prnt 'cos we want to print out the string using the 'read' cmd
    ans_str=`$gettext --domain=localeadm "Do you wish to continue? [y/n]: "`
    read ans?"${ans_str}"
    
    typeset -i yes=0 no=0

    # Checks user input with yesexpr in LC_MESSAGES of current locale
    echo "$ans" | $grep -E `locale yesexpr` > /dev/null
#    locale -ck LC_MESSAGES | grep yesexpr | awk -F'[' '{print $2}' | awk -F']' '{print $1}' | $grep ${ans} > /dev/null
    ret_val=$?
    if [ ${ret_val} -eq 0 ]; then	# If it is yes, continue on
	yes=1 
	no=0
    fi

    # Checks user input with noexpr in LC_MESSAGES of current locale
    echo "$ans" | $grep -E `locale noexpr` > /dev/null
#    locale -ck LC_MESSAGES | grep noexpr | awk -F'[' '{print $2}' | awk -F']' '{print $1}' | $grep -e ${ans} > /dev/null
    ret_val=$?
    if [ ${ret_val} -eq 0 ]; then	# If it is no, exits localeadm
	rem_lock
	exit 1 				
    fi

    # Neither yes or no, then invalid input, asks user to input again yes or no
    if [ ${yes} -eq 0 ]; then
	if [ ${no} -eq 0 ]; then
	    other=1 		
	    loc_prnt "Warning! %s is invalid, please enter y/n." log "${ans}" 
    	    check_region $LOC "install"
	fi
    fi
fi
}

###########################################################################
###################   check for an image type   ###########################
###########################################################################
#
# $1 - which cd to check for - 1of2, 2of2, langcd1 or langcd2
# $2 - locale/region to check for
#
# returns:
# 0 - image wasn't found with the locale pkgs on it
# 1 - image was found with the locale pkgs on it
# 2 - no locale pkgs on this cd - no need to check for an image. 

check_image() {
typeset -l image=$1 lang=$2
typeset -i count=0 pkg_count=0 num=2 check_count=0

if [ "$lang" = "all" ]
then
    # get a list of all the pkgs (use sort -u so we don't get dupes)
    pkg_count=`$awk '$3 ~ /'$image'/ {print $1}' $CONFIGFILE |sort -u| wc -l`
else
    #just get the pkgs needed for $lang
    pkg_count=`$awk '$3 ~ /'$image'/ && $2 ~ /'$lang'/ {print $1}' $CONFIGFILE | wc -l`
fi

if [ $pkg_count -eq 0 ] # we don't need this image for this region
then
    return 2
fi

# if we still want to get stuff from this image, keep going....
if [ "$VERBOSE" != "y" ]
then
    print -n "|"
fi

if [ "$lang" = "all" ] # looking for everything, not just one region
then
    # run through the pkg list for each CD (sort -u makes sure there's no duplicates)
    for pkg in `$awk '$3 ~ /'$image'/ {print $1}' $CONFIGFILE |sort -u`
    do
	if [ -f $INST_DIR/.order ] # if it's a solaris_1 or a DVD, just look for the pkg in the .order file
	then
	    $grep -q ${pkg} $INST_DIR/.order
	else 
	     #find $check_dir -type d -name ${pkg} -prune >/dev/null # no need for find if pkgs are $INST_DIR/$pkg
	    ls $INST_DIR | $grep -q $pkg
	fi
	if [ $? -eq 0 ] # if the pkg has been found
	then
	    count=`expr $count + 1`
	    if [ "$VERBOSE" = "y" ]
	    then
		loc_prnt "package %s found" logvb $pkg
	    else
		print -n "."
	    fi
	    else 
	    if [ "$VERBOSE" = "y" ]
	    then
		loc_prnt "package %s not found" logvb $pkg
	    else
		print -n "."   
	    fi
	fi
    done
    # don't think we need this bit any more, do we? - KC
    #if [ -f /usr/sadm/lib/localeadm/pkgs_list.txt ]
    #then
	#rm /usr/sadm/lib/localeadm/pkgs_list.txt
    #fi

else
    # run through the pkg list for each CD for just the region wanted
    # e.g. awk '$3 ~ /'solaris_2'/ && $2 ~ /'neu'/ {print $i}'
    for pkg in `$awk '$3 ~ /'$image'/ && $2 ~ /'$lang'/ {print $1}' $CONFIGFILE`
    do
	ls $INST_DIR | $grep -q $pkg
	if [ "$?" = "0" ]
	then
	    count=`expr $count + 1`
	    if [ "$VERBOSE" = "y" ]
	    then
		loc_prnt "package %s found" logvb $pkg
	    else
		print -n "."
	    fi
	    else 
	    if [ "$VERBOSE" = "y" ]
	    then
		loc_prnt "package %s not found" logvb $pkg
	    else
		print -n "."   
	    fi
	fi
    done
fi

if [ "$VERBOSE" != "y" ]
then
    print -n "|"
fi

echo
    
if [ $count -eq $pkg_count ]
then
    return 1
else
    return 0
fi

}

###########################################################################
###################    add locale function      ###########################
###########################################################################
#
# $1 - region to add
# $2 - test mode

add_locales() {

typeset -i arr_index=0 rcount=0 daemons=0 fails=0 num_fails=0
typeset -l forlist # the list of disks to install from

if [ "$2" = "y" ] # test mode
then
    loc_prnt "Adding packages for %s (%s)  - Test Mode" log "$SEL_STR" "$SEL_REGION"
else 
    loc_prnt "Adding packages for %s (%s)" log "$SEL_STR" "$SEL_REGION"
fi
echo

# first check if the locale is already installed
### changing this to change the check from "$region" to "($region)" as "ja" matches some
### strings in the l10n'ed swedish locales_list file. - KC

rcount=`$grep "($SEL_REGION)" $LOCALES_LIST | $grep -v "incomplete" | wc -l`

# start with solaris_* [1-5 in order], then langcd.

if [ $MESSAGES -eq 1 ] # if we only want messages, or we don't want messages
then
    if [ $rcount -gt 0 ] # locale was installed without msgs
    then # we only need the langcd
	forlist="${langcdImages[*]}"       #   "langcd1 langcd2"
	loc_prnt "Region %s's message packages will be installed." log "$SEL_REGION"
    else # we want everything but the langcd
	forlist="${solarisImages[*]}"     #  "solaris1 solaris2 solaris3 solaris4 solaris5"
	loc_prnt "Region %s will be installed without messages" log "$SEL_REGION"
    fi
else
    if [ $rcount -gt 0 ] 
    then 
	loc_prnt "Region %s is already installed on this machine. Exiting" nolog "$SEL_REGION"
	echo
	return 
    else # we need all of the disk images
	forlist="${solarisImages[*]} ${langcdImages[*]}"   #   "solaris1 solaris2 solaris3 solaris4 solaris5 langcd1 langcd2"
	loc_prnt "Region %s will be installed." log "$SEL_REGION"
    fi
fi


if [ "$2" != "y" ] # don't need to record stuff if we're just doing test mode
then
#    echo "Install_Dir=${ONE_OF_TWO_IMG} ${TWO_OF_TWO_IMG} ${LANGCD_IMG1} ${LANGCD_IMG2}" >> $LOGFILE
    echo "Install_Dir=${DEVICES[*]}" >> $LOGFILE
    echo "Region=$SEL_REGION" >> $LOGFILE
    if [ "$ALTROOT" = "y" ]
    then
	echo "Alt_Root=$ALT_ROOT_DIR" >> $LOGFILE
    fi
    echo >> $LOGFILE
fi

for cd in ${forlist} "dvd" # e.g. for cd in solaris_1 solaris_2 solaris_3 solaris_4 solaris_5 (no messages)
                           # the dvd is in config file only for the rare occasion that config file was generated from DVD image and thus the script didn't know where to place the package
                           # this way, when installing from dvd and all other packages had been already installed the "dvd" packages will be installed from the same path
do
    # check do we have the image
    get_install_dir ${DEVICE} $SEL_REGION $cd # returns either 0 (good dir) or the position in the array of the bad dir
    position=$?
#    if [[ "$position" -eq 0 && "$cd" = "dvd" ]]
    if [[ "$position" -ne 0 && "$cd" = "dvd" ]]
    then
      continue 
    fi    
    while [ $position -ne 0 ] # we have a bad dir so we need to dump it out of the array (bugid 5067857)	
    do	
	bad_dir=${INIT_DIR}
	ans_str=`$gettext --domain=localeadm "Please enter the path to this image/disk, or enter 'q' to quit:\n (if this image is on CD-ROM, please mount the disk and give the path to the CD-ROM drive e.g. /cdrom/cdrom0) \n > "`
	read dev?"${ans_str}"
	# if the user decides to quit, remove the lock file and exit
	if [ "$dev" = "q" ]
	then
	    rem_lock
	    exit 1
	fi 

	# changed to check for first, last then middle - easier check with all the new disks - KC

	if [ $position -eq 1 ] # if it's the first element in the array
	  then 
	    newdir1=${DEVICE##${bad_dir}} #strip it off the front of the array
	    newdir="${dev}${newdir1}"

	elif [ $position -eq ${#DEVICE[*]} ] # the last element
	then
	   newdir1=${DEVICE%%${bad_dir}}
	   newdir="${newdir1},${dev}"

	else # if it's one of the middle elements
	    newdir1=${DEVICE%%${bad_dir}*}
	    newdir2=${DEVICE##*${bad_dir}}
	    newdir="${newdir1},${dev},${newdir2}"
	fi
	DEVICE=${newdir}

	get_install_dir $DEVICE $SEL_REGION $cd # now need to change get_install_dir to only look for one img at a time! - KC
	position=$?
    done # end "while $position...."


    # check the disk here!!!!

    # e.g. for package in `awk '$2 ~ /'mea'/ && $3 ~ /'solaris_1'/ {print $1}'
    for package in `awk '$2 ~ /'$SEL_REGION'/ && $3 ~ /'$cd'/ {print $1}' $CONFIGFILE`
    do
	echo
	loc_prnt "Checking package %s......" nolog $package
	if [ "$ALTROOT" = "y" ] # if alternate root was set (installing somewhere other than /)....
	then
	    pkginfo -q -R $ALT_ROOT_DIR $pkg
	else
	    pkginfo -q $package
	fi

	if [ "$?" = "0" ]
	then
	    loc_prnt "Package %s is already installed. Skipping." nolog $package
	else
	    if [ "$2" = "y" ] # test mode
	    then
		loc_prnt "Adding package %s (test mode)" nolog $package
		if [ "$ALTROOT" = "y" ]
		then  
		    echo "pkgadd -d $ADD_DIR -a /usr/sadm/lib/localeadm/admin -R $ALT_ROOT_DIR $package" > /var/run/pkg.add
		    pkgadd -d $ADD_DIR -a /usr/sadm/lib/localeadm/admin -R $ALT_ROOT_DIR -s /dev/null $package 2>&1 >> /var/run/pkg.add
		else
		    echo "pkgadd -d $ADD_DIR -a /usr/sadm/lib/localeadm/admin $package" > /var/run/pkg.add
		    pkgadd -d $ADD_DIR -a /usr/sadm/lib/localeadm/admin -s /dev/null $package 2>&1 >> /var/run/pkg.add
		fi
	    else
		loc_prnt "Adding package %s" log $package
		if [ "$ALTROOT" = "y" ]
		then
		    echo "pkgadd -d $ADD_DIR -a /usr/sadm/lib/localeadm/admin -R $ALT_ROOT_DIR $package" > /var/run/pkg.add
		    pkgadd -d $ADD_DIR -a /usr/sadm/lib/localeadm/admin -R $ALT_ROOT_DIR $package 2>&1 >> /var/run/pkg.add
		else
		    echo "pkgadd -d $ADD_DIR -a /usr/sadm/lib/localeadm/admin $package" > /var/run/pkg.add
		    pkgadd -a /usr/sadm/lib/localeadm/admin -d $ADD_DIR $package 2>&1 >> /var/run/pkg.add
		fi
	    fi # end "if $2..."

	    ### changing this so that it doesn't bomb out on the first pkg that fails.... - KC
	    if [ $? -ne 0 ] # if pkgadd didn't work properly
	    then
		num_fails=`expr $num_fails + 1`

		cat /var/run/pkg.add >> /var/run/pkgadd.fail
		echo >> /var/run/pkgadd.fail
		echo "-------------------" >> /var/run/pkgadd.fail

		if [ $num_fails -gt 5 ] # 5 fails in one locale add is a pretty serious problem!
		### could change this to a higher or lower number....  KC
		then
		    loc_prnt "Too many packages have failed to add! Exiting the install." nolog
 		    loc_prnt "Please check the /var/run/pkgadd.fail file for details."
		    rem_lock
		    exit 1
		else 
		    if [ "$2" = "y" ]
		    then
			echo
			loc_prnt "There was an error testing the addition of package %s to the system." nolog $package
		    else
			echo
			loc_prnt "There was an error adding package %s to the system." log $package
		    fi
		    fails=1
		fi # end "if $num_fails..."
	    fi # end "if $?..." (pkgadd)

	    # check are there any daemons that need to be started...... 
	    # (just the files, so looking for type 'f' only)
	    $grep "etc/init.d" $ADD_DIR/$package/pkgmap | $grep -q "^1 f"
	    if [ $? -eq 0 ]
	    then
		echo "daemons"
		daemons=1
		# get the daemon name & put it into an array, make sure it's a full path (i.e. '/etc/init.d' not 'etc/init.d')
		daemon_cmds[arr_index]=`$grep "etc/init.d/" $ADD_DIR/$package/pkgmap | $grep "^1 f" | awk '{print $4}' | sed -e'/\=/d' -e 's/etc/\/etc/g'`
		arr_index=`expr $arr_index + 1`
	    fi # end "if $?..." (grep)
	fi #end "if $?..." (pkginfo)

    done # end 'for package in.....'
done  # end 'for cd in ${forlist}'


arr_index=0
# now we have to sort out starting all the IM daemons needed by UTF-8 & asian locales
startDaemons=""
if [ $daemons -eq 1 ]
then
#    loc_prnt "The following seem to be daemons that will need to be started (e.g. input method daemons) for some of these locales to work:" log
    startDaemons="The following seem to be daemons that will need to be started (e.g. input method daemons) for some of these locales to work: \n"
#    loc_prnt 
   # echo "Daemon pkgs are ${daemon_pkgs[*]}"
    for cmd in ${daemon_cmds[*]}
    do
#	loc_prnt "$cmd" log
	startDaemons="$startDaemons $cmd \n"
    done
    echo
#    loc_prnt "You will need to either start these manually or reset dtlogin for the locales to function properly" log 
     startDaemons="$startDaemons You will need to either start these manually or reset dtlogin for the locales to function properly\n"
fi

# now check were there any packages that failed
if [ $fails -eq 1 ]
then
	loc_prnt "There was an error adding some packages to the system." log
	loc_prnt "Your system may be in an unstable state. Please fix the problem and rerun \'localeadm %s\' to repair the locale." log "-a"
    	loc_prnt "Please check the /var/run/pkgadd.fail file for details." nolog
fi

# now we need to add the locale to the locales_list
if [ "$2" != "y" ]
then
    add_loc_added $SEL_REGION
    print_system q
    restart_fccache
    print_warning "added" nolog
fi
}

###########################################################################
######################  remove locale function   ##########################
###########################################################################
#
# $1 = region to remove
# $2 = test mode

rem_locales() {

typeset -i num_fails=0 fails=0

SEL_REGION=$1
check_region $SEL_REGION "uninstall"
if [ "$2" = "y" ]
then
    loc_prnt "Removing packages for %s (%s) - Test Mode" nolog "$SEL_STR" "$SEL_REGION"
else 
    loc_prnt "Removing packages for %s (%s)" log "$SEL_STR" "$SEL_REGION"
fi
echo
typeset -i pcount rcount install_flag

# first check that the locale is actually installed
if [ "$ALTROOT" = "y" ]
then
    query_locale $SEL_REGION
    rcount=$?
else
    rcount=`$grep $SEL_REGION $LOCALES_LIST | $grep -v "incomplete" | wc -l`
fi    


if [ $rcount -eq 0 ] 
then 
    loc_prnt "Region %s is not fully installed on this machine. Exiting" nolog "$SEL_REGION"
    return
fi

if [ "$2" != "y" ] # don't need to record stuff if we're just doing test mode
then
    echo "Region=$SEL_REGION" >> $LOGFILE
    if [ "$ALTROOT" = "y" ]
    then
	echo "Alt_Root=$ALT_ROOT_DIR" >> $LOGFILE
    fi
    echo >> $LOGFILE
fi

if [ $MESSAGES -eq 1 ] # we only want messages
then # we only need the langcd
    forlist="${langcdImages[*]}"              #  "langcd1 langcd2"
else
    #forlist="1of2 2of2 langcd"
    forlist="${solarisImages[*]} ${langcdImages[*]} dvd"      #   "solaris1 solaris2 solaris3 solaris4 solaris5 langcd"
                                                            #packages are marked as "dvd" in config file if DVD was used to generate the config file, these need to be removed as well
fi
#loc_prnt "Image list is %s" $forlist

for cd in ${forlist}
do
    for package in `awk '$2 ~ /'$SEL_REGION'/  && $3 ~ /'$cd'/ {print $1}' $CONFIGFILE`
    do
	install_flag=0 # reset each time around
	loc_prnt "Checking package %s......" log $package
    
	if [ "$ALTROOT"  = "y" ]
	then
	    pkginfo -q -R $ALT_ROOT_DIR $pkg
	else
	    pkginfo -q $package
	fi

	if [ $? -ne 0 ]
	then
	    loc_prnt "Package %s is already uninstalled. Skipping." nolog $package
	    echo
	else
	# have to take into account pkgs that may be needed by other installed locales
	    count=`$grep -c $package $CONFIGFILE`
	    if [ $count -gt 1 ]
	    then
		loc_prnt "More than one region uses this package. Checking installed regions...." log
		for region in `awk '$1 ~ /'$package'/ {print $2}' $CONFIGFILE`
		do
	            if [ "$region" != "$SEL_REGION" ]
		    then
		         loc_prnt "Checking if region %s is installed....." logvb $region
		          rcount=`$grep $region $LOCALES_LIST | $grep -v "incomplete" | wc -l`  #is region installed? i.e. in written in locales.list
		          if [ $rcount -ge 1 ] 
		          then 
				loc_prnt "Package %s is needed by region %s. Skipping." log $package $region
				echo
				install_flag=1
				break
		        fi       #end "if $rcount.." 
	            fi           #end "if $region..."
		done             #end "for region...."
	    fi                   #end "if $count...."

	    #echo "flag is $install_flag"
	    if [ $install_flag -eq 0 ]
	    then
		if [ "$2" == "y" ]
		then
		    loc_prnt "Removing package %s (test mode)" nolog $package
		    
		    if [ "$ALTROOT" = "y" ]
		    then
			echo "pkgrm -a /usr/sadm/lib/localeadm/admin -n -R $ALT_ROOT_DIR $package" > /var/run/pkg.rem
			#pkgrm -a /usr/sadm/lib/localeadm/admin -n -t -R $ALT_ROOT_DIR $package 2>&1 >> /var/run/pkg.rem
		    else
			echo "pkgrm -a /usr/sadm/lib/localeadm/admin -n $package" > /var/run/pkg.rem
			#pkgrm -a /usr/sadm/lib/localeadm/admin -n -t $package 2>&1 >> /var/run/pkg.rem
		    fi
		else
		    loc_prnt "Removing package %s" log $package
	
		    if [ "$ALTROOT" = "y" ]
		    then
			echo "pkgrm -a /usr/sadm/lib/localeadm/admin -n -R $ALT_ROOT_DIR $package" > /var/run/pkg.rem
			pkgrm -a /usr/sadm/lib/localeadm/admin -n -R $ALT_ROOT_DIR $package 2>&1 >> /var/run/pkg.rem
		    else
			echo "pkgrm -a /usr/sadm/lib/localeadm/admin -n $package" > /var/run/pkg.rem
			pkgrm -a /usr/sadm/lib/localeadm/admin -n $package 2>&1 >> /var/run/pkg.rem
		    fi
		fi # end "if $2...."

		### changing this so that it doesn't bomb out on the first pkg that fails.... - KC
		if [ $? -ne 0 ] # if pkgrm didn't work properly
		then
		    cat /var/run/pkg.rem >> /var/run/pkgrm.fail
		    echo >> /var/run/pkgrm.fail
		    echo "-------------------" >> /var/run/pkgrm.fail

		    num_fails=`expr $num_fails + 1`

		    if [ $num_fails -gt 5 ] # 5 fails in one locale add is a pretty serious problem!
		    ### could change this to a higher or lower number....  KC
		    then
			loc_prnt "Too many packages have failed to remove! Exiting the install." nolog
			loc_prnt "Please check the /var/run/pkgrm.fail file for details."
			rem_lock
			exit 1
		    else
			fails=1
			if [ "$2" = "y" ]
			then
			    echo
			    loc_prnt "There was an error testing the removal of package %s from the system." nolog $package
			else
			    echo
			    loc_prnt "There was an error removing package %s from the system." log $package
			fi
			echo
		    fi # end "if $num_fails....."
		fi #end "if $ERROR...."
		echo
	    fi    #end "if $install_flag...."
	fi        #end "if $?....."
    done          #end "for package...."
done              #end "for cd...."


# now check were there any packages that failed
if [ $fails -eq 1 ]
then
	loc_prnt "There was an error removing some packages from the system." log
	loc_prnt "Your system may be in an unstable state. Please fix the problem and rerun \'localeadm %s\' to repair the locale." log "-d"
    	loc_prnt "Please check the /var/run/pkgrm.fail file for details." nolog
fi

# need to clear the locale out of the locales.list
if [ "$2" != "y" ]
then
    rem_loc_added $SEL_REGION
    print_system q
    restart_fccache
    
    # check if the locale was really removed ( may not be because other regions might need the same packages... e.g region "naf")
    rcount=`$grep $SEL_REGION $LOCALES_LIST | $grep -v "incomplete" | wc -l`
    if [ $rcount -eq "0" ]
    then
      print_warning "removed" log
    else
      print_warning "removal-failed" log
    fi
fi
}

###########################################################################
#################  add to locales_added function   ########################
###########################################################################
#
# $1 = region to add to /var/sadm/system/data/locales_installed file

add_loc_added() {

add_region=$1

# get the name of the region from the config file
region_name=`$grep locname $CONFIGFILE | sed -e 's/locname//g' | $grep -i $add_region | $awk '{print $1}'`

if [ "$region_name" != "Asia" ] #Asian does not get entered for a normal install
then

#echo "DEBUG: region name is $region_name"
# find out is it in there already 
if [ `$grep -c $region_name $LOC_ADD_FILE ` -eq 0 ]
then 
 echo "s/GEOS=/GEOS=${region_name},/g" > /var/run/sedscript
fi

fi

for i in `$grep locname $CONFIGFILE | sed -e 's/locname//g'| $grep $add_region | $awk '{ for (j=3; j<=NF; j++) print $j }'`
do
    if [ `$grep -c $i $LOC_ADD_FILE ` -eq 0 ]
    then
	locs="${i},${locs}"
    fi
done

echo "s/LOCALES=/LOCALES=${locs}/g" >> /var/run/sedscript

sed -f /var/run/sedscript $LOC_ADD_FILE > /var/run/locrm

mv /var/run/locrm $LOC_ADD_FILE
rm /var/run/sedscript
}


###########################################################################
################  remove from locales_added function   ####################
###########################################################################
#
# $1 = region to remove from /var/sadm/system/data/locales_added file

rem_loc_added() {

rem_region=$1

# have to get rid of 'locname' out of final search string here 
# 'cos north america region (nam) keeps picking it up! 
region_name=`$grep locname $CONFIGFILE | sed -e 's/locname//g' | $grep -i $rem_region | $awk '{print $1}'`

#echo "region name is $region_name"

if [ "$region_name" = "Asia" ] # there are multiple geos which call themselves asia
then
    typeset -i geo_count=0
    for geo in `$grep locname $CONFIGFILE | grep "Asia" | awk '{print $3}'`
    do
	typeset -i acount=0 lcount=0 
	#echo "DEBUG: looking for $geo"
	for i in `$grep locname $CONFIGFILE | sed -e 's/locname//g'| $grep $geo | $awk '{ for (j=3; j<=NF; j++) print $j }'`
	do
	    if [ `$grep -c $i $LOC_ADD_FILE` -ne 0 ]
	    then
		acount=`expr $acount + 1`
	    fi
	done 
	lcount=`$grep locname $CONFIGFILE | sed -e 's/locname//g'| $grep $geo | $awk '{ for (j=3; j<=NF; j++) print $j }' | wc -l`
	if [ $acount -eq $lcount ] #if all teh locales are mentioned
	then
	    geo_count=`expr $geo_count + 1` #up the asian geo count by 1
	fi
    done
fi

# find out is it in there already 
if [[ `$grep -c $region_name $LOC_ADD_FILE` -ne 0  && $geo_count -le 1 ]]
then 
    echo "s/$region_name,//g" > /var/run/sedscript
    echo "s/,$region_name//g" >> /var/run/sedscript # if it's at the end of the string
    echo "s/$region_name//g" >> /var/run/sedscript # if only one region was installed with the inital install
fi

for i in `$grep locname $CONFIGFILE | sed -e 's/locname//g'| $grep $rem_region | $awk '{ for (j=3; j<=NF; j++) print $j }'`
do
    echo "s/${i},//g" >> /var/run/sedscript
    echo "s/${i}$//g" >> /var/run/sedscript # if locale is at the end of the string
done

echo
sed -f /var/run/sedscript $LOC_ADD_FILE > /var/run/locrm
rm /var/run/sedscript
mv /var/run/locrm $LOC_ADD_FILE


}


###########################################################################
######################  print warning function   ##########################
###########################################################################
#
# $1 = added or removed

print_warning() {
echo
echo
if [ "$1" = "added" ]
then
    loc_prnt "One or more locales have been added. To update the list of locales available at the login screen's \"Options->Language\" menu, please restart the
dtlogin daemon (WARNING: this will terminate any active dtlogin sessions)" nolog
    echo
    loc_prnt "Please log out and login again to use the new locale(s) at your desktop. If you are not intending to use the new locale(s) with the GUI desktop, you can start using the new locale(s) immediately by setting the LC_* environment variables." nolog
    echo
    print $startDaemons
elif [ "$1" = "removal-failed" ]
then
    loc_prnt "System failed to uninstal specified region. The reason is probably that other regions are dependent on the same packages, try removing other regions that use the same packages first." nolog
    echo
else
    loc_prnt "One or more locales have been removed. To update the list of locales available at the login screen's \"Options->Language\" menu, please restart the dtlogin daemon (WARNING: this will terminate any active dtlogin sessions)" nolog
fi
echo
}

###########################################################################
######################  Fix locale function   #############################
###########################################################################
#
# $1 = the locale to fix

fix_locale() {

# find the last time the locale was used 
lastregion=$1

check_region $lastregion "fix"

for i in `ls -rt /var/sadm/install/logs/localeadmin_* `
do 
    lastlog=`grep -l "Region\=$SEL_REGION" $i`
done

if [ -z $lastlog ]
then
    loc_prnt "Error: There don't seem to have been any previous operations on %s (%s)" nolog "$SEL_STR" "$SEL_REGION"
    rem_lock
    exit 1
fi

# get all the arguments used last time
op=`$grep Operation\= $lastlog`
lastop=${op##Operation=}

alt=`grep Alt_Root $lastlog`
if [ $? -eq 0 ]
then
    ALTROOT="y"
    ALT_ROOT_DIR=${alt##=}
fi

if [ "$lastop" = "install" ]
then 
    if [ -z $DEVICE ]
    then
	echo "no dir supplied"
	dir=`grep Install_Dir\= $lastlog`
	lastdir=${dir##Install_Dir=}
	set -A DEVICES `echo $lastdir | awk '{for(i = 1; i <= NF; i++) print $i}'`
    else
	get_devices $DEVICE
	get_install_dir $DEVICES $SEL_REGION
    fi
    rem_locales $lastregion
    add_locales $lastregion
else
    rem_locales $lastregion
fi
}

###########################################################################
######################  Query locale function   ###########################
###########################################################################

query_locale() {
SEL_REGION=$1
DEVICE=$2
typeset -i result=0 core=0 langcd=0

check_region $SEL_REGION "check"

# check for core cluster pkgs first
if [ "$ALTROOT" = "y" ]
then
    checkPath="alt"
else
    checkPath="mach"
fi

check_locale $SEL_REGION "$checkPath" "c_solaris"
core=`expr $core + $?`
expected=`expr ${#solarisImages[*]} '*' 2`  # check_locale succeeded on all CDs, all packages from all CDs are installed

# check if there are any packages at all for this region -- this can be important for e.g. new regions
regionPackages=`$grep $SEL_REGION $CONFIGFILE | $grep -v "locname" | wc -l`
if [ "$regionPackages" -eq 0 ]
then
   core=0 
fi

if [ $core -eq 2 ]
then
    # we have something on the system, so check for the rest of the pkgs
    for disk in ${solarisImages[*]}       #  solaris1 solaris2 solaris3 solaris4 solaris5
    do
	check_locale $SEL_REGION "$checkPath" "$disk"
	result=`expr $result + $?`
    done
    
#    print "DEBUG:: expected:$expected, result:$result\n"
    if [ "$result" -eq "$expected" ] # we have a solaris1, solaris 2, solaris3, solaris4, solaris5
    then
        for disk in ${langcdImages[*]}
	do
	    check_locale $SEL_REGION "$checkPath" "$disk"
	    langcd=`expr $langcd + $?`
	done
    fi
fi

#print "DEBUG $SEL_REGION langcd: $langcd, solaris:$result, core:$core\n"

#if [[ $result -eq $expected && $core -eq 2 && langcd -ge 2 ]] # if we have a messages as well
if [[ $result -eq $expected && $core -eq 2 ]] 
then
    loc_prnt "The %s region (%s) is installed on this system" nolog "$SEL_STR" "$SEL_REGION"
    echo
    return 1    
#elif [[ $result -eq $expected && $core -eq 2 ]] # no messages but a solaris1, solaris2, solaris3, solaris4 and solaris5
#then
#    loc_prnt "The %s region (%s) is installed on this system without messages" nolog "$SEL_STR" "$SEL_REGION"
#    echo
#    return 1
elif [ core -eq 2 ]
then
    loc_prnt "The %s region (%s) is installed on this system, but some packages may be missing." nolog "$SEL_STR" "$SEL_REGION"
    loc_prnt "Please run localeadm with the -v option to find the list of missing packages." nolog 
else
    loc_prnt "The %s region (%s) is not installed on this system" nolog "$SEL_STR" "$SEL_REGION"
    echo
    return 0
fi
# we should never get here, but let's put in a fail return just in case
return 0

}

###########################################################################
#######################  get devices function  ############################
###########################################################################
#
# $1 - dir list taken in from the user

get_devices(){
# if we have multiple images, they should be comma separated with no spaces
typeset -i num=0 arr=0 arrnext=0

num=`echo $1 | awk -F"," '{print NF}'`

# separate all the dirs out
set -A DEVICES `echo $1 | awk -F"," '{for(i = 1; i <= NF; i++) print $i}'`
arr=`expr $arr + 1` 
}




###########################################################################
#####################  get install dir function   #########################
###########################################################################
#
# $1 = DEVICES - array of dirs passed in as arg
# $2 = $LOC - locale chosen by user
# $3 = image - image we are looking for


get_install_dir() {


typeset -l LOC=$2 image=$3
get_devices $1
arr_size=${#DEVICES[*]}
set -A devices ${DEVICES[*]}
typeset -i retval=0 arr=0 break=0

while [[ arr -lt arr_size && break -eq 0 ]]
do
  retval=0 # reset return val so we don't clobber ourselves each time through...... - KC
    INIT_DIR=${devices[${arr}]} 

    if [ -d $INIT_DIR/Solaris_$OS_VER ] # we have a 1of 2, 2of2 or combined image
    then 
	INST_DIR=$INIT_DIR/Solaris_$OS_VER/Product
    elif [ -d $INIT_DIR ] # assume just a dir
    then
	INST_DIR=${devices[arr]}
   else
	loc_prnt "Warning! The directory specified does not exist \n (%s) \n" nolog $INIT_DIR
	typeset -i retval=`expr $arr + 1`
	return $retval
    fi

    # are there any packages in the specified path?

    typeset -i pkgcount=`ls $INST_DIR | $grep -c SUNW`

    if [ $pkgcount -eq 0 ]
    then
	loc_prnt "Warning! No Solaris packages exist in %s" nolog $INST_DIR
	typeset -i retval=`expr $arr + 1`
    else
	# make sure that all pkgs have the same architecture - bugid 5052631
	if [ -f /var/run/arch.txt ] # make sure this file is clear before we start!
	then
	    rm /var/run/arch.txt 
	fi

	for package in `awk '$2 ~ /'$LOC'/ {print $1}' $CONFIGFILE`
	do

	    if [ -f  $INST_DIR/$package/pkginfo ]
	    then
		tmp_arch=`grep ARCH $INST_DIR/$package/pkginfo | sed -e's/ARCH=//g'`
		echo $tmp_arch >> /var/run/arch.txt
	    fi
	done
        if [ -f /var/run/arch.txt ]
        then
	  sort -u /var/run/arch.txt > /var/run/arch_final.txt

	  if [ `wc -l /var/run/arch_final.txt | awk '{print $1}'` -gt 1 ]
          then
	    typeset -i retval=`expr $arr + 1`
	    echo
	    loc_prnt "The packages in %s do not appear to be all of the same architecture." nolog $INST_DIR
 	    loc_prnt "Please check these packages and re-run localeadm."
	    echo
	    break=1
	  else
	    pkg_arch=`more /var/run/arch_final.txt`
          fi
	# clean up all the temp files
	  if [ -f /var/run/arch_final.txt ]
	  then
	    rm /var/run/arch_final.txt
	  fi
	    rm /var/run/arch.txt
        fi
	if [ "$pkg_arch" != $ARCH -a break -eq 0 ] # if the pkgs aren't the same arch as the system
 	then
	    typeset -i retval=`expr $arr + 1`
	    echo
	    loc_prnt "The packages in \n%s \nappear to be the incorrect architecture for your system." nolog $INST_DIR
	    loc_prnt "(packages are %s, your system is %s)" nolog $pkg_arch $ARCH
 	    loc_prnt "Please check these packages and re-run localeadm."
	    echo
	   # return $retval
	    break=1
        elif [ break -eq 0 ]	
        then
	    loc_prnt "Checking for a $image in config file" log
	    check_image $image $LOC
	    result=$?
	    if [ $result -eq 1 ]
	    then
		loc_prnt "We have a $image: \n%s" log $INST_DIR
                ADD_DIR=${INST_DIR}
		break=1
	    elif [ $result -eq 2 ]
	    then
		loc_prnt "We don't need a $image" logvb
                ADD_DIR=""
		break=1
	    else
	      loc_prnt "No $image image has been found in \n%s " nolog $INST_DIR
	      echo
	      typeset -i retval=`expr $arr + 1`
	    fi
	fi	    
    fi
    arr=`expr $arr + 1`
done

# break -eq 0 means that we didn't find the cd, but overpassed the devices array boundaries
if [[ break -eq 0 && "$2" != "all" && "$image" = "solaris1" ]]
then
    loc_prnt "You need at least a solaris1 image to add any locales." nolog
    loc_prnt "Please provide the path to a solaris1 image." nolog
    echo    
fi
return $retval
}



###########################################################################
########################  check user function  ############################
###########################################################################
check_rights(){

for auth in `auths | tr , " "`
do
    [ "$auth" = "solaris.*" ] && break
    [ "$auth" = "solaris.admin.patchmgr.*" ] && break
    [ "$auth" = "solaris.admin.patchmgr.write" ] && break
done

if [[ "$auth" = "solaris.*" || "$auth" = "solaris.admin.patchmgr.*" || "$auth" = "solaris.admin.patchmgr.write" ]]
then
    RIGHTS="y"
fi

if [ "$RIGHTS" != "y" ]
then
    loc_prnt "Warning! You do not have the correct authorisation to modify system packages." nolog
    loc_prnt "Please contact your system administrator about obtaining this authorization." nolog
    rm /usr/sadm/lib/localeadm/lock
    exit
fi
}

###########################################################################
####################    set up the logfile     ############################
###########################################################################

make_log() {
CMD=$1
DATE=`date "+%Y-%m-%d"`
if [ -f /var/sadm/install/logs/localeadmin_${CMD}.$DATE ]
then # have to go to $DATE.1, $DATE.2 etc.
    if [ -f /var/sadm/install/logs/localeadmin_${CMD}.$DATE.* ]
    then
	typeset -i datenum=1
	while [ -f /var/sadm/install/logs/localeadmin_${CMD}.$DATE.$datenum ]
	do
	    datenum=`expr $datenum + 1`
	done    
	LOGFILE=/var/sadm/install/logs/localeadmin_${CMD}.$DATE.$datenum
    else
	LOGFILE=/var/sadm/install/logs/localeadmin_${CMD}.$DATE.1
    fi
else
    LOGFILE=/var/sadm/install/logs/localeadmin_${CMD}.$DATE
fi
date > $LOGFILE
echo "Operation=$CMD" >> $LOGFILE

loc_prnt "Log file is %s" nolog $LOGFILE

PKGTMP=/var/run/pkg.${CMD}   # MP is this variable PKGTMP used elsewhere too???
}

###########################################################################
####################    set up a lockfile     #############################
###########################################################################

make_lock() {

if [ -L /var/run/localeadm.lock.* ]
then
    lock=`ls -la /var/run/localeadm.lock.* | awk '{ print $NF}'`
    pid=`ls -la /var/run/localeadm.lock.* |sed 's/.*lock.//'`

    loc_prnt "Warning: Another localeadm process (PID %s) seems to be running on display %s" nolog $pid $lock
    echo
    loc_prnt "Please wait until this process is finished, and if necessary remove the /var/run/localeadm.lock file" nolog
    exit 0
else
    if [ "$DISPLAY" = "" ]
    then
	DISPLAY="${HOST}:0.0"	
    fi
#    LOCKPID=`ps -f| awk '/localead/ && !/awk/ {print $2}'|head -n 1`
    LOCKPID=$$
    ln -s $DISPLAY /var/run/localeadm.lock.$LOCKPID
fi
}

###########################################################################
####################    delete the lockfile     ###########################
###########################################################################

rem_lock() {

#    LOCKPID=`ps -f| awk '/localead/ && !/awk/ {print $2}'|head -n 1`
    LOCKPID=$$
    if [ -L /var/run/localeadm.lock.$LOCKPID ]
    then
	rm /var/run/localeadm.lock.$LOCKPID
    fi
}

###########################################################################
######################## create config file     ###########################
###########################################################################
create_config () {

# Remove the temp file if it exists at start

if [ -f $CONFIGFILE".tmp" ]
then
        rm $CONFIGFILE".tmp"
fi

selection=0
choice=0
repeat=0

if [ ! -f $CONFIGFILE ]
then
	loc_prnt "No old config file $CONFIGFILE found, please make sure the config file exists before continuing. You can either rename the $CONFIGFILE.old if it exists or you need to reinstall the localeadm package"
	return
fi


# loop while selection is invalid

while [[ $selection -eq 0 ]] 
do

        if [[ $repeat -eq 1 ]]
        then
        echo ""
        loc_prnt "Incorrect input choice: please input another choice"
        fi

        echo ""
        loc_prnt "Please select the option that was used to install Solaris"
        echo ""
        loc_prnt "1.  CD installation/net installed CD images"
        loc_prnt "2.  DVD installation/net installed combined image"
        echo ""
        loc_prnt "Please enter your choice: "
        read choice

        if [[ "$choice" == "1" ]] 
        then
                selection=1
        fi

        if [[ "$choice" == "2" ]] 
        then
                selection=1
        fi

        repeat=1
done

# If user has selected the cd installation option

if [[ $choice -eq 1 ]] 
then

# if Locale_config_S[release].txt.old doesn't exist, move Locale_config_S[release].txt to Locale_config_S[release].txt.old

if [ ! -f $CONFIGFILE".old" ]
then
        cp $CONFIGFILE $CONFIGFILE".old"
fi

echo ""
echo "------------------------------------------------------"
loc_prnt "CD installation/net installed CD image option selected"
echo "------------------------------------------------------"

set -A sources ${solarisImages[*]} ${langcdImages[*]}        #  solaris1 solaris2 solaris3 solaris4 solaris5 langcd1 langcd2 

# run the retrievecd.pl program for each of the installation sources

#for index in 0 1 2 3 4 5 6
#for((index=0; index<${#sources[*]}; index++))
index=0
while [ index -lt ${#sources[*]} ]
do

  echo ""
  echo "-------------------------------------"
  loc_prnt "Looking for install image %s" nolog ${sources[index]}
  echo "-------------------------------------"

  echo ""
  loc_prnt "Please enter path for install image %s: " nolog ${sources[index]}
  read cdpath

  while [ ! -d ${cdpath} ]
  do
	echo ""
	loc_prnt "%s not found: Please insert image %s and enter path: " nolog $cdpath ${sources[index]};
	read cdpath
  done

  cdfound=0

  while [ "$cdfound" -eq 0 ] 
  do
	CDLABEL="SPARC"
 	if [[ "$ARCH" = "i386" ]]
        then
 		CDLABEL="X86";
 	fi;

#	if [ "${sources[index]}" == "solaris1" ] 
#	then
#		# Path should have a s0 directory above it if it is solaris1
#
#		testpath="$cdpath/s0"
#		if [ ! -d ${testpath} ] 
#		then
#			testpath="$cdpath/Solaris*"
#			if [ ! -d ${testpath} ]
#			then
#				echo ""
#				loc_prnt "%s not found, please insert image %s and enter path: " nolog ${sources[index]} ${sources[index]};
#				read cdpath
#			else
#				cdfound=1
#				cdpath="$cdpath/Solaris_*/Product"
#			fi
#		else 
#			cdfound=1
#			cdpath="$cdpath/s0/Solaris_*/Product"
#		fi	
#        else
             is_correct_cd ${sources[index]}
#        fi
  done

# Program continues if the correct CD path has been found
  echo ""
  loc_prnt "Install image %s found ... searching" nolog ${sources[index]};

# Run the retrieve cd data perl program to gather l10n package info
  /usr/bin/perl /usr/sadm/lib/localeadm/retrievecd.pl ${sources[index]} $CONFIGFILE $cdpath
  echo ""
  loc_prnt "Finished searching install cd %s" nolog ${sources[index]}

  index=`expr $index + 1`
done

echo ""
loc_prnt "Finished retrieving locale data"
echo ""

# run the generate config file program

echo "-----------------------------------------------"
loc_prnt "Generating %s config file..." nolog $CONFIGFILE
echo "-----------------------------------------------"

/usr/bin/perl /usr/sadm/lib/localeadm/gen_configfile.pl $CONFIGFILE

echo ""
echo "-----------------------------------------------"
loc_prnt "Finished Creating new file %s " nolog $CONFIGFILE
echo "-----------------------------------------------"

echo ""
loc_prnt "Original Config file can be found at %s\.old" nolog $CONFIGFILE
loc_prnt "New config file stored at %s" nolog $CONFIGFILE
echo ""

# if Locale_config_S[release].txt.old doesn't exist, move Locale_config_S[release].txt to Locale_config_S[release].txt.old
# and move Locale_config_S[release].txt.bak to Locale_config_S[release].txt

if [ ! -f $CONFIGFILE".old" ]
then
        cp $CONFIGFILE $CONFIGFILE".old"
        mv $CONFIGFILE".bak" $CONFIGFILE
fi

# if Locale_config_S[release].txt.old exists, move Locale_config_S[release].txt.bak Locale_config_S[release].txt

if [ -f $CONFIGFILE".old" ]
then
        mv $CONFIGFILE".bak" $CONFIGFILE
fi

# Remove tempfile if it still exists

if [ -f $CONFIGFILE".tmp" ]
then
        rm $CONFIGFILE".tmp"
fi

fi

# If user has selected the combined image installation option

if [[ $choice -eq 2 ]] 
then

# if Locale_config_S[release].txt.old doesn't exist, move Locale_config_S[release].txt to Locale_config_S[release].txt.old

if [ ! -f $CONFIGFILE".old" ]
then
        cp $CONFIGFILE $CONFIGFILE".old"
fi

echo ""
echo "------------------------------------------------------------------"
loc_prnt "DVD installation/net installed combined image option selected"
echo "------------------------------------------------------------------"
echo ""

loc_prnt "Please enter path for install DVD/combined image: ";
read cdpath

# Repeat input prompt to user while the path is not valid

while [ ! -d ${cdpath} ]
do
	echo ""
	loc_prnt "%s not found: Please insert image and enter path: " nolog $cdpath;
	read cdpath
done

# Flag variable to detect if the path points to the installation image

combinedfound=0

# Loop that tests the path is correct for the combined image, or else prompts
# until the correct path is entered

while [ "$cdfound" -eq 0 ] 
do
		
		# Path should have a Solaris_10 and Product directories above it.
		testpath="$cdpath/Solaris*/Product"
		if [ ! -d ${testpath} ] 
		then
			echo ""
			loc_prnt "Image not found, please insert image and enter path: ";
			read cdpath
		else 
			cdfound=1
		fi
done

# Program continues if the correct DVD path has been found

echo ""
loc_prnt "Install image %s found ... searching" nolog $cdpath

cdpath="$cdpath/Solaris*/Product"

# run the retrievecombined.pl program to retrieve data from combined image
# run the retrievecd.pl program with param "dvd", this way the script will try to keep the information about where packages are on individual CDs, only in the case it can't figure out the location from $CONFIGFILE, it will claim it is on DVD

/usr/bin/perl /usr/sadm/lib/localeadm/retrievecd.pl "dvd" $CONFIGFILE $cdpath

echo ""
loc_prnt "Finished retrieving locale data"

# run the generate config file program to create the config file

echo ""
echo "-----------------------------------------------"
loc_prnt "Generating %s config file..." nolog $CONFIGFILE
echo "-----------------------------------------------"
echo ""

/usr/bin/perl /usr/sadm/lib/localeadm/gen_configfile.pl $CONFIGFILE

echo "-----------------------------------------------"
loc_prnt "Finished Creating new file %s " nolog $CONFIGFILE
echo "-----------------------------------------------"

echo ""
loc_prnt "Original Config file can be found at %s\.old" nolog $CONFIGFILE
loc_prnt "New config file stored at %s" nolog $CONFIGFILE
echo ""

# if Locale_config_S[release].txt.old doesn't exist, move Locale_config_S[release].txt to Locale_config_S[release].txt.old
# and move Locale_config_S[release].txt.bak to Locale_config_S[release].txt

if [ ! -f $CONFIGFILE".old" ]
then
        cp $CONFIGFILE $CONFIGFILE".old"
        mv $CONFIGFILE".bak" $CONFIGFILE 
fi

# if Locale_config_S[release].txt.old exists, move Locale_config_S[release].txt.bak Locale_config_S[release].txt

if [ -f $CONFIGFILE".old" ]
then
        mv $CONFIGFILE.bak $CONFIGFILE 
fi

# Remove tempfile if it still exists

if [ -f $CONFIGFILE".tmp" ]
then
        rm $CONFIGFILE".tmp"
fi

fi

}


###########################################################################
##################  prompt user to create config file  ####################
###########################################################################

prompt_user() {

if [ ! -f $CONFIGFILE".old" ]   # Checking if config file has been freshly created
then loc_prnt "You do not appear to have created a fresh config file since you began using this application." 
    loc_prnt "If you have a set of Solaris install images available to you, it is recommended that you do so before proceeding."

    echo

    typeset -l ans 
    while [ -z $ans ]; do
	echo       # using gettext rather than a call to loc_prnt 'cos we want to print out thestring using the 'read' cmd
	ans_str=`$gettext --domain=localeadm "Do you wish to create a new config file? [y/n]: "`
	read ans?"${ans_str}"
    done
  
    typeset -i yes=0 no=0

    # Checks user input with yesexpr in LC_MESSAGES of current locale
    echo "$ans" | $grep -E `locale yesexpr` > /dev/null
#    locale -ck LC_MESSAGES | grep yesexpr | awk -F'[' '{print $2}' | awk -F']' '{print $1}' | $grep ${ans} > /dev/null
    ret_val=$?
    if [ ${ret_val} -eq 0 ]; then       # If it is yes, continue on
        yes=1
        no=0
        create_config
    fi

    # Checks user input with noexpr in LC_MESSAGES of current locale
    echo "$ans" | $grep -E `locale noexpr` > /dev/null
#    locale -ck LC_MESSAGES | grep noexpr | awk -F'[' '{print $2}' | awk -F']' '{print $1}' | $grep -e ${ans} > /dev/null
    ret_val=$?
    if [ ${ret_val} -eq 0 ]; then       # If it is no, copies to a .old file so the user is not prompted the next time l'admin is run
	cp $CONFIGFILE $CONFIGFILE".old"
	yes=0
	no=1
	echo
	loc_prnt "You have chosen not to create a new config file. Should you wish to do so in future, run localeadm -C at any time." 
	echo
	loc_prnt "localeadm will continue in a few moments ..."
	echo
	sleep 15
    fi

    # Neither yes or no, then invalid input, asks user to input again yes or no
    if [ ${yes} -eq 0 ]; then
        if [ ${no} -eq 0 ]; then
            other=1
	    echo
            loc_prnt "Warning! %s is invalid, please enter y/n." log "${ans}"
            prompt_user # 
        fi
    fi
fi



}

###########################################################################
#######################    main loop    ###################################
###########################################################################

TEST="n" # default value is no test mode
#global variables
typeset HOST=`uname -n`
typeset ARCH=`uname -p`

typeset -i MESSAGES=0 sub_list=0 add_rem=0 COMBINED_IMG=0 exit_val=0 daemons=0
typeset -l ALTROOT="n"

typeset CONFIG_FLAG=0	#Used to avoid unnecessary prompts

RELEASE=`uname -r`
OS_VER=${RELEASE#*.} #have to hack for testing on linux
#OS_VER=10

CONFIGFILE=/usr/sadm/lib/localeadm/Locale_config_S${OS_VER}.txt

SELFPID=`ps -f| awk '/localead/ && !/awk/ {print $2}'|head -n 1`
trap 'rm -f /var/run/localeadm.lock.$SELFPID 2>&1 > /dev/null' 0 1 2 3 10 11 15 #Need to remove the lockfile if the running of the application is interupted

#if [ ! -f $CONFIGFILE ]
#then
#    loc_prnt "Error: The configuration file for this release (%s) does not seem to exist on your system. If you have a set of Solaris images available to you, please run localeadm -C to create it. If not, contact your system administrator." nolog $CONFIGFILE
#    rem_lock
#    exit 1
#fi

#prompt_user 




LOC_ADD_FILE=/var/sadm/system/data/locales_installed

if [ -w /usr/sadm/lib/localeadm/ ]
then
    LOCALES_LIST=/var/sadm/system/data/locales.list
    if [ ! -L /var/run/locales.list ]
    then
	ln -s /var/sadm/system/data/locales.list /var/run/locales.list
    fi
else
    LOCALES_LIST=/var/run/locales.list
fi

while getopts a:cCd:f:hlLmnq:r:R:stv opts
do
case $opts in
    a)
	if [[ "$OPTARG" = "r" || "$OPTARG" = "-r" ]]
	then
	    add_rem=`expr $add_rem + 1`
	elif [ "$CMD" = "rem" ]
	then
	    add_rem=`expr $add_rem + 1`
	elif [ "$OPTARG" = "t" ]
	then
	    TEST="y"
	fi
	    CMD="add"	    
	    LOC=$OPTARG
	;;
    c)
	sub_list=`expr $sub_list + 1`
	P_CMD="code"
	;;

    C)
        create_config 
	CONFIG_FLAG=1
	rem_lock
        exit 1
	;;
    d)
	if [ "$CMD" = "list" ]
	then
	    CMD=listall
	fi
	DEVICE="$OPTARG"
	;;
    f)
	CMD="fix"
	LOC=$OPTARG
	;;
    h)
	print_help
	exit 0
	;;
    l) 
	CMD="list"
	if [ ! $P_CMD ]
	then
	    P_CMD="locale"
	fi
	;;
    m)
	MESSAGES=1
	;;
    q)
	CMD="query"
	LOC=$OPTARG
	;;
    r)
	if [[ "$OPTARG" = "a" || "$OPTARG" = "-a" ]]
	then
	    add_rem=`expr $add_rem + 1`
	elif [ "$CMD" = "add" ]
	then
	    add_rem=`expr $add_rem + 1`
	elif [ "$OPTARG" = "t" ]
	then
	    TEST="y"
	fi
	CMD="rem"
	LOC="$OPTARG"
	;;
    R)
	ALTROOT="y"
	ALT_ROOT_DIR=$OPTARG
	;;
    s)
	sub_list=`$expr $sub_list + 1`
	P_CMD="short"
	;;
    t) 
	TEST="y"
	;;
    v)
	loc_prnt "Verbose mode" nolog
	VERBOSE="y"
	;;
    \?)
	print_help_msg $1
	exit 0
	;;
esac

# just check to see did we enter any conflicting subcommands....
if [ $sub_list -gt 1 ]
then
    loc_prnt "Warning: You can enter only one listing subcommand at a time." nolog
    loc_prnt "Please enter -lc or -ls" nolog
    exit_val=1
    break
fi

if [ $add_rem -gt 0 ]
then 
    echo
    loc_prnt "Error: you cannot add and remove locales at the same time." nolog
    loc_prnt "Please choose either '-a' (add) or '-r' (remove) as an option" nolog
    echo
    exit_val=1
    break
fi
done

# now we have the args sorted out, let's actually do something

if [[ ! -f $CONFIGFILE && $CONFIG_FLAG -eq 0 ]]
then
    loc_prnt "Error: The configuration file for this release (%s) does not seem to exist on your system. If you have a set of Solaris images available to you, please run localeadm -C to create it. If not, contact your system administrator." nolog $CONFIGFILE
    rem_lock
    exit 1
fi

if [ $CONFIG_FLAG -eq 0 ]
then
    prompt_user 
fi    


# set up a lock file so you can't run more than one invocation at a time
make_lock

case $CMD in
    add)
    	check_rights
	if [ ! $DEVICE ]
	then
	    loc_prnt "Error: You must supply a location to add packages from." nolog
	    echo "e.g. localeadm -a weu -d /cdrom/cdrom0"
  	    echo
	    exit_val=1
	    break
	else
	    make_log "install"
	    if [ ! -f $LOCALES_LIST ]
	    then
		loc_prnt "Analyzing system for addition. This may take a minute." nolog
		print_system q
	    fi
	    SEL_REGION=$LOC
	    check_region $LOC "install"

	    # do a quick check to make sure we're not trying to add a locale that's already there
	    rcount=`$grep $SEL_REGION $LOCALES_LIST | $grep -v "incomplete" | wc -l`
	    msg_count=`$grep  $SEL_REGION $LOCALES_LIST | $grep -q "no messages"`
	    if [[ $rcount -gt 0 && $msg_count -ne 0 ]] 
	    then
		loc_prnt "Region %s is already installed on this machine. Exiting" nolog $SEL_REGION
		echo
		exit_val=0
		break
	    else		
		add_locales $LOC $TEST
	    fi
	fi
	;;
    fix)
	fix_locale $LOC
	;;
    listall)	
	get_devices $DEVICE
	print_system $P_CMD $TEST "all"
	;;
    list)
	print_system $P_CMD $TEST
	;;
    query)
	query_locale $LOC $DEVICE
	# have to reverse the normal exit values as I use o/p of query_locale as a counter elsewhere
	if [ $? -eq 1 ]
	then 
	    exit_val=0
	    break
 	elif [ $? -eq 0 ]
	then
	    exit_val=1
	    break
	fi
	;;
    rem)
	check_rights
	make_log "uninstall"

	if [ ! -f $LOCALES_LIST ]
	then
	    loc_prnt "Analyzing system for remove. This may take a minute." nolog
	    print_system q
	fi

	rem_locales $LOC $TEST
	;;
esac

# once we're finished, remove the lock file
rem_lock

exit $exit_val # make sure we exit cleanly if we get this far.........