#!/bin/bash
touch /tmp/installer.lock
sync

# creating log location
installerlog='/var/log/sut/sut_installer.log';

temp1=$1

echo "input is $1"  >> $installerlog

/opt/sut/bin/sut /waitforupgrade >> $installerlog  2>&1 ;

# Function to ask for confirmation
ask_confirmation() {
    local prompt="Proceed with application account creation? (yes/no): "
    local attempts=0
    local max_attempts=3  # Limit the number of attempts

    echo
    echo "This host application uses virtual NIC (VNIC) to communicate with iLO."
    echo "For communication using VNIC, an app account in iLO needs to be created."
    echo "As part of the app account, an app token will be generated and the same"
    echo "will be stored securely in the system TPM. Note that the app token and"
    echo "app account will be automatically removed when the application is"
    echo "uninstalled. For more information on app account please refer to the"
    echo "documentation."
    echo

    while true; do
        CONFIRMATION=""  # Clear any previous value
        read -p "$prompt" CONFIRMATION < /dev/tty
        echo "DEBUG: CONFIRMATION='$CONFIRMATION'" >> $installerlog ;
        case "$CONFIRMATION" in
            [Yy][Ee][Ss]|[Yy])
				echo "Proceeding with application account creation..."
                echo "Proceeding with application account creation..." >> $installerlog ;
                # Interactive mode: Prompt for credentials
                read -p "Enter iLO username: " ILO_USERNAME < /dev/tty
                if [ -z "$ILO_USERNAME" ]; then
                    echo "Username not provided. Skipping application account creation."
					echo "Username not provided. Skipping application account creation." >> $installerlog ;
                    return 1
                fi
                read -s -p "Enter iLO password (input will be hidden): " ILO_PASSWORD < /dev/tty
                if [ -z "$ILO_PASSWORD" ]; then
                    echo -e "\nPassword not provided. Skipping application account creation."
					echo "Password not provided. Skipping application account creation." >> $installerlog ;
                    return 1
                fi
                echo

                export ILO_USERNAME
                export ILO_PASSWORD
                echo "Creating application account for username: $ILO_USERNAME"
				echo "Creating application account for username: $ILO_USERNAME"  >> $installerlog ;
                return 0
                ;;
            [Nn][Oo]|[Nn])
                echo "Skipping application account creation. User can create the application account using sut appaccount create command later."
				echo "Skipping application account creation. User can create the application account using sut appaccount create command later." >> %{log}
                return 1
                ;;
            *)
                echo "Invalid input. Please answer 'yes' or 'no'."
				echo "Invalid input. Please answer 'yes' or 'no'." >> $installerlog ;
                ((attempts++))
                if [ $attempts -ge $max_attempts ]; then
                    echo "Maximum attempts reached. Exiting."
					echo "Maximum attempts reached. Exiting." >> $installerlog ;
                    return 1
                fi
                ;;
        esac
    done
}

main() {
    if [ -n "$PS1" ] || [ -t 1 ]; then
        #echo "Detecting system..."
        /opt/sut/bin/sut -detectilo >> $installerlog  2>&1 ;
	ret_val=$?

        if [ $ret_val -eq 0 ]; then
            ret_val_confirm=0
            if [ -z "${ILO_USERNAME+x}" ] || [ -z "${ILO_PASSWORD+x}" ]; then
                echo "Environment variable ILO_USERNAME  or ILO_PASSWORD is unset."
				echo "Environment variable ILO_USERNAME  or ILO_PASSWORD is unset." >> $installerlog ;
                ask_confirmation
                ret_val_confirm=$?
            elif [ -z "$ILO_USERNAME" ] || [ -z "$ILO_PASSWORD" ]; then
                echo "Environment variable ILO_USERNAME or ILO_PASSWORD is empty."
				echo "Environment variable ILO_USERNAME or ILO_PASSWORD is empty." >> $installerlog ;
                ask_confirmation
                ret_val_confirm=$?
            else
				echo "ask_confirmation: return value : $ret_val_confirm" >> $installerlog ;

                if [ $ret_val_confirm -eq 0 ]; then
                    echo "Environment variable ILO_USERNAME is set and non-empty."
                    echo "Environment variable ILO_USERNAME is set and non-empty." >> $installerlog ;
                    echo
                    echo "This host application uses virtual NIC (VNIC) to communicate with iLO."
                    echo "Virtual NIC requires app account or iLO credentials to communicate to iLO."
                    echo "Found iLO credentials in env variables. Using the same to create app account."
                    echo
                fi
            fi

            echo "ask_confirmation: return value : $ret_val_confirm" >> %{log}
            if [ $ret_val_confirm -eq 0 ]; then
				/opt/sut/bin/sut -getapptoken "$ILO_USERNAME" "$ILO_PASSWORD"	>> $installerlog  2>&1 ;
				ret_val=$?
				if [ $ret_val -eq 0 ]; then		 
                	echo "Successfully created the application account"
					echo "Successfully created the application account" >> $installerlog ;
				elif [ $ret_val -eq 1 ]; then
					echo "Application account already exists"
					echo "Application account already exists" >> $installerlog ;
				else
					echo "Application account creation failed"
					echo "Application account creation failed" >> $installerlog ;
				fi
            fi
		elif [ $ret_val -eq 1 ]; then
            echo "iLO 5/6 version detected. Application account creation skipped" >> $installerlog ;
		elif [ $ret_val -eq 2 ]; then
			echo "Detecting iLO version failed"
            echo "Detecting iLO version failed. Application account could not be created" >> $installerlog ;
		elif [ $ret_val -eq 4 ]; then
			echo "Unable to access iLO using virtual NIC. Please ensure virtual NIC is enabled in iLO. Ensure that virtual NIC in the host OS is configured properly. Refer to documentation for more information."
            echo "Unable to access iLO using virtual NIC. Please ensure virtual NIC is enabled in iLO. Ensure that virtual NIC in the host OS is configured properly. Refer to documentation for more information." >> %{log}
		else
			echo "Invalid case." >> $installerlog ;
        fi
    fi
}
cat <<HP_CONFIG>>/dev/null
<configurations>
<configuration short_name="sut.linux">
  <parameter name="PollingIntervalInMinutes">
   <depends>
	  <dependent name="" value=""/>
   </depends>
  <user_prompt>
	<![CDATA[Enter Polling interval in minutes. Minimum 5 minutes Maximum 1440 minutes. ]]>
  </user_prompt>
  <default value="5" />
  <output type="file_variable" filename="/usr/local/sut/sut_cfg.dat" value="5" encrypt="0"/>
  <requirements>
	<required_for_installation value="NO" /><!--Required fields for installation. Value is YES indicates must paramter for the deployment -->
	<input_requirements>
	  <minimum_length>0</minimum_length>
	  <maximum_length>12</maximum_length>
	  <acceptable_characters>
		<![CDATA[0-9]]>
	  </acceptable_characters>
	  <required_format>
		<![CDATA[*]]>
	  </required_format>
	  <user_visible value="yes" />
	  <user_editable value="yes" />
	  <password_field value="no" />
	</input_requirements>
  </requirements>
</parameter>
    <parameter name="Mode" >
      <user_prompt>
        <![CDATA[Mode in which SUT runs. ]]>
      </user_prompt>
      <default value="AutoDeploy;AutoStage;AutoDeployReboot;OnDemand" />
      <output type="file_variable" filename="/usr/local/sut/sut_cfg.dat" value="OnDemand" encrypt="0"/>
      <requirements>
        <required_for_installation value="no" />
        <input_requirements>
          <minimum_length>0</minimum_length>
          <maximum_length>24</maximum_length>
          <acceptable_characters>
            <![CDATA[*]]>
          </acceptable_characters>
          <required_format>
            <![CDATA[*]]>
          </required_format>
          <user_visible value="yes" />
          <user_editable value="yes" />
          <password_field value="no" />
        </input_requirements>
      </requirements>
      <depends>
        <dependent name="" value=""/>
      </depends>
    </parameter>
    <parameter name="StagingDirectory" >
      <user_prompt>
        <![CDATA[Enter the directory where the staging has to be done. The default path for staging directory is /var/tmp/sut/stagingdirectory.]]>
      </user_prompt>
      <default value="" />
      <output type="file_variable" filename="/usr/local/sut/sut_cfg.dat" value="" encrypt="0"/>
      <requirements>
        <required_for_installation value="no" />
        <input_requirements>
          <minimum_length>0</minimum_length>
          <maximum_length>255</maximum_length>
          <acceptable_characters>
            <![CDATA[0..9A..Z;a..z;-/]]>
          </acceptable_characters>
          <required_format>
            <![CDATA[*]]>
          </required_format>
          <user_visible value="yes" />
          <user_editable value="yes" />
          <password_field value="no" />
        </input_requirements>
      </requirements>
      <depends>
        <dependent name="" value=""/>
      </depends>
    </parameter>
</configuration>
</configurations>
HP_CONFIG

echo $(date) "SUT is installed successfully" >> $installerlog ;

#Creating soft link for sut command to take effect on the same command prompt
#Remove and re-create the soft link if it exists

rm -f /usr/sbin/sut >> $installerlog  2>&1 ;
ln -s /opt/sut/bin/sut /usr/bin/sut >> $installerlog  2>&1 ;
ln -s /opt/sut/bin/sut /usr/sbin/sut >> $installerlog  2>&1 ;

if [ $? -eq 0 ]
then
	echo $(date) "iSUT Symbolic link is created successfully" >> $installerlog ;
else
	echo $(date) "iSUT Symbolic link is creation failed" >> $installerlog ;
fi

#Creating soft link for hpsut command, which will be a top level script on sut to take effect on the same command prompt
#Remove and re-create the soft link if it exists
#If symbolic link for hpsut is created in /usr/sbin, it is removed in postun section of 1.6.5 or 1.0.1 during an upgrade(happens because of debranding). Thus creating it in /usr/bin.


rm -rf /tmp/installer.lock
mkdir -p /usr/local/sut && touch /usr/local/sut/sut_recovery.dat


#migrate DB if required
dbVersion=6_5_0_0


if [ "$1" = "configure" ]; then
    if [ -n "$2" ]; then
        echo "Upgrade or reinstall from version $2"
    else
        echo "Fresh install"
		main
    fi
fi

/opt/sut/bin/sut -migratedb >> $installerlog 2>&1 ;
/opt/sut/bin/sut -installer -version | tr -d '\n' | awk '{print $13}'
/opt/sut/bin/sut -installer -deployfinish >> /dev/null  &
#touch /opt/sut/.GPGimportkeys