#!/bin/sh
# Copyright (C) 2020-2021, 2025 NVIDIA Corporation. ALL RIGHTS RESERVED.
# Copyright 2016, 2017 Cumulus Networks, Inc.  All rights reserved

export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/cumulus/bin

# Fixups needed first time a system is booted.
# This runs early in boot from the cumulus-firstboot.service, on the
# first boot after an image is installed. It runs as soon as
# possible after the root filesystem is mounted read/write.

# We only run once.  Disable ourselves as our very first action, so
# if something goes wrong, we won't run again.
[ -f /etc/cumulus-upgrade-firstboot-done ] && exit 0
touch /etc/cumulus-upgrade-firstboot-done

vx=0
# Determine if we are on VX platform or not.  If so, leave tty1 enabled
if [ -e /etc/cumulus/switchd.env ]; then
    . /etc/cumulus/switchd.env
    [ "$VX" = "-vx" ] && vx=1
fi

# Clean up any older leftover staged area
STG_DIR="/var/installer"

# Check if directory exists
if [ -d "$STG_DIR" ]; then
    echo "upgrade-firstboot: $STG_DIR exists. Cleaning up..."
  
    # Clean up directory contents
    rm -rf "$STG_DIR"
  
    # Check if cleanup was successful
    if [ $? -eq 0 ]; then
        echo "upgrade-firstboot : Cleanup successful."
    else
        echo "upgrade-firstboot : Cleanup of $STG_DIR failed. Check permissions."
    fi
fi

# Run all of the scripts in /usr/lib/cumulus/upgrade-firstboot.d/*.firstboot
#
UPGRADE_FIRSTBOOT_DIR="/usr/lib/cumulus/upgrade-firstboot.d"
[ -d "${UPGRADE_FIRSTBOOT_DIR}" ] && {
    scripts=$(/bin/ls ${UPGRADE_FIRSTBOOT_DIR}/*.firstboot 2>/dev/null) && {
        for s in ${scripts} ; do
            echo "firstboot executing ${s}"
            ${s}
            echo "firstboot finished ${s}"
        done
    }
}

exit 0
