#!/bin/sh
# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB
# This file is public domain and comes with NO WARRANTY of any kind

# MySQL daemon start/stop script.

# Usually this is put in /etc/init.d (at least on machines SYSV R4 based
# systems) and linked to /etc/rc3.d/S99mysql and /etc/rc0.d/K01mysql.
# When this is done the mysql server will be started when the machine is
# started and shut down when the systems goes down.

# Comments to support chkconfig on RedHat Linux
# chkconfig: 2345 64 36
# description: A very fast and reliable SQL database engine.

# Comments to support LSB init script conventions
### BEGIN INIT INFO
# Provides: mysql
# Required-Start: $local_fs $network $remote_fs
# Should-Start: ypbind nscd ldap ntpd xntpd
# Required-Stop: $local_fs $network $remote_fs
# Default-Start:  2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start and stop MySQL
# Description: MySQL is a very fast and reliable SQL database engine.
### END INIT INFO

# If you install MySQL on some other places than @prefix@, then you
# have to do one of the following things for this script to work:
#
# - Run this script from within the MySQL installation directory
# - Create a /etc/my.cnf file with the following information:
#   [mysqld]
#   basedir=<path-to-mysql-installation-directory>
# - Add the above to any other configuration file (for example ~/.my.ini)
#   and copy my_print_defaults to /usr/bin
# - Add the path to the mysql-installation-directory to the basedir variable
#   below.
#
# If you want to affect other MySQL variables, you should make your changes
# in the /etc/my.cnf, ~/.my.cnf or other MySQL configuration files.

# If you change base dir, you must also change datadir. These may get
# overwritten by settings in the MySQL configuration files.

basedir=
datadir=

# Default value, in seconds, afterwhich the script should timeout waiting
# for server start.
# Value here is overriden by value in my.cnf.
# 0 means don't wait at all
# Negative numbers mean to wait indefinitely
service_startup_timeout=900

# Lock directory for RedHat / SuSE.
lockdir='/var/lock/subsys'
lock_file_path="$lockdir/mysql"

# The following variables are only set for letting mysql.server find things.

# Set some defaults
mysqld_pid_file_path=
if test -z "$basedir"
then
  basedir=@prefix@
  bindir=@bindir@
  if test -z "$datadir"
  then
    datadir=@localstatedir@
  fi
  sbindir=@sbindir@
  libexecdir=@libexecdir@
else
  bindir="$basedir/bin"
  if test -z "$datadir"
  then
    datadir="$basedir/data"
  fi
  sbindir="$basedir/sbin"
  libexecdir="$basedir/libexec"
fi

# datadir_set is used to determine if datadir was set (and so should be
# *not* set inside of the --basedir= handler.)
datadir_set=

#
# Use LSB init script functions for printing messages, if possible
#
lsb_functions="/lib/lsb/init-functions"
if test -f $lsb_functions ; then
  . $lsb_functions
else
  log_success_msg()
  {
    echo " SUCCESS! $@"
  }
  log_failure_msg()
  {
    echo " ERROR! $@"
  }
fi

PATH="/sbin:/usr/sbin:/bin:/usr/bin:$basedir/bin"
export PATH

mode=$1    # start or stop

[ $# -ge 1 ] && shift

other_args="$*"   # uncommon, but needed when called from an RPM upgrade action
           # Expected: "--skip-networking --skip-grant-tables"
           # They are not checked here, intentionally, as it is the resposibility
           # of the "spec" file author to give correct arguments only.

case `echo "testing\c"`,`echo -n testing` in
    *c*,-n*) echo_n=   echo_c=     ;;
    *c*,*)   echo_n=-n echo_c=     ;;
    *)       echo_n=   echo_c='\c' ;;
esac

parse_server_arguments() {
  for arg do
    case "$arg" in
      --basedir=*)  basedir=`echo "$arg" | sed -e 's/^[^=]*=//'`
                    bindir="$basedir/bin"
		    if test -z "$datadir_set"; then
		      datadir="$basedir/data"
		    fi
		    sbindir="$basedir/sbin"
		    libexecdir="$basedir/libexec"
        ;;
      --datadir=*)  datadir=`echo "$arg" | sed -e 's/^[^=]*=//'`
		    datadir_set=1
	;;
      --pid-file=*) mysqld_pid_file_path=`echo "$arg" | sed -e 's/^[^=]*=//'` ;;
      --service-startup-timeout=*) service_startup_timeout=`echo "$arg" | sed -e 's/^[^=]*=//'` ;;
    esac
  done
}

wait_for_pid () {
  verb="$1"           # created | removed
  pid="$2"            # process ID of the program operating on the pid-file
  pid_file_path="$3" # path to the PID file.

  i=0
  avoid_race_condition="by checking again"

  while test $i -ne $service_startup_timeout ; do

    case "$verb" in
      'created')
        # wait for a PID-file to pop into existence.
        test -s "$pid_file_path" && i='' && break
        ;;
      'removed')
        # wait for this PID-file to disappear
        test ! -s "$pid_file_path" && i='' && break
        ;;
      *)
        echo "wait_for_pid () usage: wait_for_pid created|removed pid pid_file_path"
        exit 1
        ;;
    esac

    # if server isn't running, then pid-file will never be updated
    if test -n "$pid"; then
      if kill -0 "$pid" 2>/dev/null; then
        :  # the server still runs
      else
        # The server may have exited between the last pid-file check and now.
        if test -n "$avoid_race_condition"; then
          avoid_race_condition=""
          continue  # Check again.
        fi

        # there's nothing that will affect the file.
        log_failure_msg "The server quit without updating PID file ($pid_file_path)."
        return 1  # not waiting any more.
      fi
    fi

    echo $echo_n ".$echo_c"
    i=`expr $i + 1`
    sleep 1

  done

  if test -z "$i" ; then
    log_success_msg
    return 0
  else
    log_failure_msg
    return 1
  fi
}

# Get arguments from the my.cnf file,
# the only group, which is read from now on is [mysqld]
if test -x "$bindir/my_print_defaults";  then
  print_defaults="$bindir/my_print_defaults"
else
  # Try to find basedir in /etc/my.cnf
  conf=/etc/my.cnf
  print_defaults=
  if test -r $conf
  then
    subpat='^[^=]*basedir[^=]*=\(.*\)$'
    dirs=`sed -e "/$subpat/!d" -e 's//\1/' $conf`
    for d in $dirs
    do
      d=`echo $d | sed -e 's/[ 	]//g'`
      if test -x "$d/bin/my_print_defaults"
      then
        print_defaults="$d/bin/my_print_defaults"
        break
      fi
    done
  fi

  # Hope it's in the PATH ... but I doubt it
  test -z "$print_defaults" && print_defaults="my_print_defaults"
fi

#
# Read defaults file from 'basedir'.   If there is no defaults file there
# check if it's in the old (depricated) place (datadir) and read it from there
#

extra_args=""
if test -r "$basedir/my.cnf"
then
  extra_args="-e $basedir/my.cnf"
fi

parse_server_arguments `$print_defaults $extra_args mysqld server mysql_server mysql.server`

#
# Set pid file if not given
#
if test -z "$mysqld_pid_file_path"
then
  mysqld_pid_file_path=$datadir/`@HOSTNAME@`.pid
else
  case "$mysqld_pid_file_path" in
    /* ) ;;
    * )  mysqld_pid_file_path="$datadir/$mysqld_pid_file_path" ;;
  esac
fi

case "$mode" in
  'start')
    # Start daemon

    # Safeguard (relative paths, core dumps..)
    cd $basedir

    echo $echo_n "Starting MySQL"
    if test -x $bindir/mysqld_safe
    then
      # Give extra arguments to mysqld with the my.cnf file. This script
      # may be overwritten at next upgrade.
      $bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" $other_args >/dev/null &
      wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$?

      # Make lock for RedHat / SuSE
      if test -w "$lockdir"
      then
        touch "$lock_file_path"
      fi

      exit $return_value
    else
      log_failure_msg "Couldn't find MySQL server ($bindir/mysqld_safe)"
    fi
    ;;

  'stop')
    # Stop daemon. We use a signal here to avoid having to know the
    # root password.

    if test -s "$mysqld_pid_file_path"
    then
      # signal mysqld_safe that it needs to stop
      touch "$mysqld_pid_file_path.shutdown"

      mysqld_pid=`cat "$mysqld_pid_file_path"`

      if (kill -0 $mysqld_pid 2>/dev/null)
      then
        echo $echo_n "Shutting down MySQL"
        kill $mysqld_pid
        # mysqld should remove the pid file when it exits, so wait for it.
        wait_for_pid removed "$mysqld_pid" "$mysqld_pid_file_path"; return_value=$?
      else
        log_failure_msg "MySQL server process #$mysqld_pid is not running!"
        rm "$mysqld_pid_file_path"
      fi

      # Delete lock for RedHat / SuSE
      if test -f "$lock_file_path"
      then
        rm -f "$lock_file_path"
      fi
      exit $return_value
    else
      log_failure_msg "MySQL server PID file could not be found!"
    fi
    ;;

  'restart')
    # Stop the service and regardless of whether it was
    # running or not, start it again.
    if $0 stop  $other_args; then
      $0 start $other_args
    else
      log_failure_msg "Failed to stop running server, so refusing to try to start."
      exit 1
    fi
    ;;

  'reload'|'force-reload')
    if test -s "$mysqld_pid_file_path" ; then
      read mysqld_pid <  "$mysqld_pid_file_path"
      kill -HUP $mysqld_pid && log_success_msg "Reloading service MySQL"
      touch "$mysqld_pid_file_path"
    else
      log_failure_msg "MySQL PID file could not be found!"
      exit 1
    fi
    ;;
  'status')
    # First, check to see if pid file exists
    if test -s "$mysqld_pid_file_path" ; then
      read mysqld_pid < "$mysqld_pid_file_path"
      if kill -0 $mysqld_pid 2>/dev/null ; then
        log_success_msg "MySQL running ($mysqld_pid)"
        exit 0
      else
        log_failure_msg "MySQL is not running, but PID file exists"
        exit 1
      fi
    else
      # Try to find appropriate mysqld process
      mysqld_pid=`@PIDOF@ $libexecdir/mysqld`

      # test if multiple pids exist
      pid_count=`echo $mysqld_pid | wc -w`
      if test $pid_count -gt 1 ; then
        log_failure_msg "Multiple MySQL running but PID file could not be found ($mysqld_pid)"
        exit 5
      elif test -z $mysqld_pid ; then
        if test -f "$lock_file_path" ; then
          log_failure_msg "MySQL is not running, but lock file ($lock_file_path) exists"
          exit 2
        fi
        log_failure_msg "MySQL is not running"
        exit 3
      else
        log_failure_msg "MySQL is running but PID file could not be found"
        exit 4
      fi
    fi
    ;;
    *)
      # usage
      basename=`basename "$0"`
      echo "Usage: $basename  {start|stop|restart|reload|force-reload|status}  [ MySQL server options ]"
      exit 1
    ;;
esac

exit 0


#!/bin/sh
#
# A simple startup script for mysqld_multi by Tim Smith and Jani Tolonen.
# This script assumes that my.cnf file exists either in /etc/my.cnf or
# /root/.my.cnf and has groups [mysqld_multi] and [mysqldN]. See the
# mysqld_multi documentation for detailed instructions.
#
# This script can be used as /etc/init.d/mysql.server
#
# Comments to support chkconfig on RedHat Linux
# chkconfig: 2345 64 36
# description: A very fast and reliable SQL database engine.
#
# Version 1.0
#

basedir=/usr/local/mysql
bindir=/usr/local/mysql/bin

if test -x $bindir/mysqld_multi
then
  mysqld_multi="$bindir/mysqld_multi";
else
  echo "Can't execute $bindir/mysqld_multi from dir $basedir";
  exit;
fi

case "$1" in
    'start' )
        "$mysqld_multi" start $2
        ;;
    'stop' )
        "$mysqld_multi" stop $2
        ;;
    'report' )
        "$mysqld_multi" report $2
        ;;
    'restart' )
        "$mysqld_multi" stop $2
        "$mysqld_multi" start $2
        ;;
    *)
        echo "Usage: $0 {start|stop|report|restart}" >&2
        ;;
esac


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!--
   Copyright (C) 2003 MySQL AB
   Use is subject to license terms

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
-->
<plist version="1.0">
<dict>
	<key>IFPkgDescriptionDeleteWarning</key>
	<string></string>
	<key>IFPkgDescriptionDescription</key>
	<string>MySQL @VERSION@@MYSQL_SERVER_SUFFIX@ for Mac OS X</string>
	<key>IFPkgDescriptionTitle</key>
	<string>MySQL @VERSION@@MYSQL_SERVER_SUFFIX@ for Mac OS X</string>
	<key>IFPkgDescriptionVersion</key>
	<string>@VERSION@@MYSQL_SERVER_SUFFIX@</string>
	</dict>
</plist>


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!--
   Copyright (C) 2003, 2008 MySQL AB
   Use is subject to license terms

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
-->
<plist version="1.0">
<dict>
	<key>CFBundleGetInfoString</key>
	<string>MySQL @VERSION@@MYSQL_SERVER_SUFFIX@</string>
	<key>CFBundleIdentifier</key>
	<string>com.mysql.mysql</string>
	<key>CFBundleName</key>
	<string>MySQL</string>
	<key>CFBundleShortVersionString</key>
	<string>@MYSQL_NUMERIC_VERSION@</string>
	<key>IFPkgFlagAllowBackRev</key>
	<false/>
	<key>IFPkgFlagAuthorizationAction</key>
	<string>RootAuthorization</string>
	<key>IFPkgFlagDefaultLocation</key>
	<string>/usr/local</string>
	<key>IFPkgFlagInstallFat</key>
	<false/>
	<key>IFPkgFlagIsRequired</key>
	<false/>
	<key>IFPkgFlagRelocatable</key>
	<false/>
	<key>IFPkgFlagRestartAction</key>
	<string>NoRestart</string>
	<key>IFPkgFlagRootVolumeOnly</key>
	<true/>
	<key>IFPkgFlagUpdateInstalledLanguages</key>
	<false/>
	<key>IFPkgFormatVersion</key>
	<real>0.10000000149011612</real>
</dict>
</plist>


#!/bin/sh
#
# Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; version 2
# of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the Free
# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA

#
# postflight - this script will be executed after the MySQL PKG
# installation has been performed.
#
# This script will install the MySQL privilege tables using the
# "mysql_install_db" script and will correct the ownerships of these files
# afterwards.
#

if cd @prefix@ ; then
	if [ ! -f data/mysql/db.frm ] ; then
		./sbin/mysqld --initialize --datadir=@prefix@/data --basedir=@prefix@
	fi

	if [ -d data ] ; then
		chown -R @MYSQLD_USER@ data
	fi
else
	exit $?
fi


#!/bin/sh

# Copyright (C) 2003, 2005 MySQL AB
# Use is subject to license terms
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; version 2
# of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the Free
# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA

#
# preflight - this script will be executed before the MySQL PKG
# installation will be performed.
#
# If this package has been compiled with a prefix ending with "mysql" (e.g.
# /usr/local/mysql or /opt/mysql), it will rename any previously existing
# directory with this name before installing the new package (which includes
# a symlink named "mysql", pointing to the newly installed directory, which
# is named mysql-<version>)
#

PREFIX="@prefix@"
BASENAME=`basename $PREFIX`

if [ -d $PREFIX -a ! -L $PREFIX -a $BASENAME = "mysql" ] ; then
	mv $PREFIX $PREFIX.bak
fi


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!--
   Copyright (C) 2003 MySQL AB
   Use is subject to license terms

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
-->
<plist version="1.0">
<dict>
	<key>Description</key>
	<string>MySQL @VERSION@@MYSQL_SERVER_SUFFIX@</string>
	<key>OrderPreference</key>
	<string>None</string>
	<key>Provides</key>
	<array>
		<string>MySQL</string>
	</array>
	<key>Uses</key>
	<array>
		<string>Network</string>
		<string>Resolver</string>
	</array>
	</dict>
</plist>


#!/bin/bash

# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under both the MIT license found in the
# LICENSE-MIT file in the root directory of this source tree and the Apache
# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
# of this source tree.

set -euxo pipefail

if ! command -v opam &> /dev/null
then
    echo "opam is not installed, which is a dependency for building targets in ocaml."
    exit
fi

if [ -z "$OPAM_SWITCH_PREFIX" ]; then
    echo "OPAM_SWITCH_PREFIX is undefined. First execute \`eval (\$opam env)\` and then try running $0 again."
    exit
fi

# Link 'shim/third-party/ocaml/standard_library'.
if [ ! -L shim/third-party/ocaml/standard_library ]; then
  (cd shim/third-party/ocaml && ln -s "$(ocamlopt.opt -config | grep standard_library: | awk '{ print $2 }' )" standard_library)
else
    echo "Link 'shim/third-party/ocaml/standard_library' exists. To overwrite it, first remove it and run $0 again"
fi

# Link 'third-party/ocaml/opam'.
if [ ! -L shim/third-party/ocaml/opam ]; then
  (cd shim/third-party/ocaml && ln -s "$OPAM_SWITCH_PREFIX" opam)
else
    echo "Link 'shim/third-party/ocaml/opam' exists. To overwrite it, first remove it and run $0 again"
fi


#!/bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under both the MIT license found in the
# LICENSE-MIT file in the root directory of this source tree and the Apache
# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
# of this source tree.

set -e

# - Apply a debug prefix map for the current directory
# to make debug info relocatable.
# - Use $TMPDIR for the module cache location. This
# will be set to a unique location for each RE action
# which will avoid sharing modules across RE actions.
# This is necessary as the inputs to the modules will
# be transient and can be removed at any point, causing
# module validation errors to fail builds.
if [ -n "$INSIDE_RE_WORKER" ]; then
    MODULE_CACHE_PATH="$TMPDIR/module-cache"
else
    # When building locally we can use a shared module
    # cache as the inputs should remain at a fixed
    # location.
    MODULE_CACHE_PATH="/tmp/buck-module-cache"
fi

module_cache_path_args=()
if [ -z "$EXPLICIT_MODULES_ENABLED" ]; then
    module_cache_path_args+=("-module-cache-path")
    module_cache_path_args+=("$MODULE_CACHE_PATH")
fi

"$@" -debug-prefix-map "$PWD"=. "${module_cache_path_args[@]}"

OUTPUT_PATHS=()
for ARG in "$@"
do
    if [ "${FOUND_OUTPUT_ARG}" = 1 ]; then
        OUTPUT_PATHS+=( "${ARG}" )
    fi
    FOUND_OUTPUT_ARG=0
    if [ "${ARG}" = "-o" ] || [ "${ARG}" = "-emit-module-path" ] || [ "${ARG}" = "-emit-objc-header-path" ]; then
        FOUND_OUTPUT_ARG=1
    fi
done

if [ ${#OUTPUT_PATHS[@]} -eq 0 ]; then
    >&2 echo "No output paths found, ensure output args are not passed in argfiles"
    exit 1
fi

for OUTPUT_PATH in "${OUTPUT_PATHS[@]}"
do
    # We've observed cases where the Swift compiler would return with a zero exit code but
    # would not have created the output file, correctly a non-zero exit code in such cases.
    if [ ! -f "${OUTPUT_PATH}" ]; then
        >&2 echo "Output file does not exist: '${OUTPUT_PATH}'"
        exit 1
    fi
done


#! /bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under both the MIT license found in the
# LICENSE-MIT file in the root directory of this source tree and the Apache
# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
# of this source tree.

set -eu

$1 "${@:2}" 1>&2


#!/bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under both the MIT license found in the
# LICENSE-MIT file in the root directory of this source tree and the Apache
# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
# of this source tree.

PYTHONPATH="$(dirname "$(dirname "$(dirname "$(realpath "$0")")")")"
export PYTHONPATH
exec python3 -m unittest sourcedb_merger.tests


#!/bin/bash
set -e

obmc_dir=$(realpath "$(dirname "$0")")
. $obmc_dir/yocto_repos.sh

FETCH_ONLY=0
while [[ $# -gt 0 ]]
do
  case $1 in
    -f|--fetch-only)
      FETCH_ONLY=1
      shift
      ;;

    *)
      shift
      ;;
  esac
done

if [ ! -d ./yocto ]; then
  mkdir ./yocto
fi

git remote add yocto-poky \
    https://git.yoctoproject.org/git/poky || true
git remote add yocto-meta-openembedded \
    https://github.com/openembedded/meta-openembedded.git || true
git remote add yocto-meta-security \
    https://git.yoctoproject.org/git/meta-security || true
git remote add yocto-lf-openbmc \
    https://github.com/openbmc/openbmc.git || true

for branch in ${branches[@]}
do
  # Make the branch if it does not exist.
  if [ ! -d ./yocto/$branch ]; then
    mkdir ./yocto/$branch
  fi

  if [[ ${branch} == lf-* ]]; then
      real_branch="${branch/lf-/}"
  else
      real_branch="${branch}"
  fi

  repos=${branch/-/_}_repos[@]
  for repo in ${!repos}
  do
    repo_name=${repo%%:*}
    commit_id=${repo##*:}

    if [ "lf-openbmc" = "$repo_name" ]; then
        repo_name="lf-openbmc"
        repo_path="./yocto/${branch}"
        repo_patch_var="${real_branch}_openbmc_patch"
    else
        repo_path="./yocto/${branch}/${repo_name}"
        repo_patch_var="${branch}_${repo_name/-/_}_patch"
    fi

    # Remove the repo in the branch
    if [ -d ${repo_path} ]; then
      rm -rf ${repo_path}
    fi

    # Fetch the repo branch
    git fetch yocto-${repo_name} ${real_branch}

    # Add specific commit of repo into yocto/branch/repo/ worktree
    if [ $FETCH_ONLY -eq 0 ]; then
      git worktree add -f ${repo_path} ${commit_id}
      if [ -n "${!repo_patch_var}" ]; then
          for patch in ${!repo_patch_var}; do
              git -C ${repo_path} am \
                $(realpath ./github/yocto/patches/${patch})
          done
      fi
    fi
  done
done


branches=(
    rocko
    lf-master
    lf-dunfell
    lf-kirkstone
    lf-langdale
)

rocko_repos=(
    meta-openembedded:eae996301
    meta-security:74860b2
    poky:5f660914cd # bitbake: bitbake-user-manual: Fixed section head typo
)
rocko_poky_patch="0001-rocko-backport-support-for-override.patch 0002-Remove-checks-on-python.patch 0003-Add-support-to-build-on-centOS9.patch"
lf_master_repos=(
    lf-openbmc:15c7c77bf
)
lf_dunfell_repos=(
    lf-openbmc:c2858f16b
)
lf_kirkstone_repos=(
    lf-openbmc:821a859c1
)
lf_langdale_repos=(
    lf-openbmc:f4e5dde7f
)


if [[ "$(realpath /proc/self/fd/0)" == *"/pts/"* ]]; then
    export TMOUT=__SSH_TMOUT__
fi


if [[ "$(realpath /proc/self/fd/0)" == *"ttyS"* ]]; then
    export TMOUT=__TMOUT__
fi


#!/bin/bash
#
# Copyright 2018-present Facebook. All Rights Reserved.
#
### BEGIN INIT INFO
# Provides:          setup-bic-cache
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Set Cachcing for Bridge IC info
### END INIT INFO
# shellcheck disable=SC1091
source /usr/local/fbpackages/utils/ast-functions

echo -n "Setup Caching for Bridge IC info.."

/usr/local/bin/bic-cache 0 > /dev/null 2>&1 &

echo "done."


#!/bin/bash
#
# Copyright 2018-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          setup-sensord
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Setup sensor monitoring
### END INIT INFO
# shellcheck disable=SC1091
echo -n "Setup bic monitoring... "

runsv /etc/sv/bicmond > /dev/null 2>&1 &

echo "done."


#!/bin/sh

rm -f ../bios-util/*.pyc
rm -rf ./*.pyc


#!/bin/bash
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA

FRUID_UTIL="/usr/local/bin/fruid-util"
FW_UTIL="/usr/bin/fw-util"
KV_CMD="/usr/bin/kv"
SLOT_NAME=""
RUN_MODE="manual"

SCRIPT_PATH="${0}"

update_crashdump_history()
{
  l_SLOT_NUM=$1
  l_CURT_DTIME=$2

  HISTORY_KEY="crashdump_history_slot$l_SLOT_NUM"

  HISTORY_RECORD=$($KV_CMD get "$HISTORY_KEY" persistent)
  HIST_INDEX_1=$(echo "$HISTORY_RECORD" | awk -F',' '{ print $1 }')
  HIST_INDEX_2=$(echo "$HISTORY_RECORD" | awk -F',' '{ print $2 }')

  OUT_STR="$l_CURT_DTIME"
  if [ -n "$HIST_INDEX_1" ]; then
    OUT_STR="$OUT_STR,$HIST_INDEX_1"
  fi
  if [ -n "$HIST_INDEX_2" ]; then
    OUT_STR="$OUT_STR,$HIST_INDEX_2"
  fi

  $KV_CMD set "$HISTORY_KEY" "$OUT_STR" persistent
}

clear_crashdump_archive()
{
  l_SLOT_NUM=$1
  HISTORY_KEY="crashdump_history_slot$l_SLOT_NUM"

  HISTORY_RECORD=$(${KV_CMD} get "$HISTORY_KEY" persistent)
  hist_dtime_1=$(echo "$HISTORY_RECORD" | awk -F',' '{ print $1 }')
  hist_dtime_2=$(echo "$HISTORY_RECORD" | awk -F',' '{ print $2 }')
  hist_dtime_3=$(echo "$HISTORY_RECORD" | awk -F',' '{ print $3 }')

  for i in /mnt/data/crashdump_slot"$l_SLOT_NUM"*.tar.gz
  do
    file_dtime=$(basename "$i" | awk -F'.' '{print $1}' | awk -F'_' '{print $3}')
    if [ "$file_dtime" = "$hist_dtime_1" ]; then
      continue
    elif [ "$file_dtime" = "$hist_dtime_2" ]; then
      continue
    elif [ "$file_dtime" = "$hist_dtime_3" ]; then
      continue
    else
      rm "$i"
    fi
  done
}

dump_sensor_history()
{
  l_SLOT=$1
  l_SENSOR_HISTORY=180

  /usr/local/bin/sensor-util "$l_SLOT" --history $l_SENSOR_HISTORY \
   && /usr/local/bin/sensor-util spb --history $l_SENSOR_HISTORY \
   && /usr/local/bin/sensor-util nic --history $l_SENSOR_HISTORY
}

dump_sensor_threshold()
{
  l_SLOT=$1

  /usr/local/bin/sensor-util "$l_SLOT" --threshold \
   && /usr/local/bin/sensor-util spb --threshold \
   && /usr/local/bin/sensor-util nic --threshold
}

script_filename()
{
  N=${SCRIPT_PATH##*/}
  N=${N#[SK]??}
  echo "$N"
}

for i in "$@"; do
  case "$1" in
    -e|--event)
      RUN_MODE="event"
      shift
      ;;
    --*|-*=) # unsupported flags
      echo "Error: Unsupported flag $i" >&2
      exit 1
      ;;
    *) # preserve positional arguments
      SLOT_NAME="$i"
      shift
      ;;
  esac
done

case $SLOT_NAME in
    slot1)
      SLOT_NUM=1
      ;;
    slot2)
      SLOT_NUM=2
      ;;
    slot3)
      SLOT_NUM=3
      ;;
    slot4)
      SLOT_NUM=4
      ;;
    *)
      echo "Usage: $(script_filename) {slot1|slot2|slot3|slot4}"
      exit 1
      ;;
esac

# We only support event triggered crashdump for now
if [ "$RUN_MODE" = "manual" ]; then
  echo "$(script_filename): Manual trigger not supported"
  exit 1
fi

# File format autodump<slot_id>.pid (See pal_is_crashdump_ongoing()
# function definition)
PID_FILE="/var/run/autodump${SLOT_NUM}.pid"

CURT_DTIME=$(date +"%Y%m%d-%H%M%S")
CRASHDUMP_FILE="/tmp/crashdump_${SLOT_NAME}"
CRASHDUMP_DECODED_FILE="/tmp/crashdump_${SLOT_NAME}_mca"
CRASHDUMP_LOG_ARCHIVE="/mnt/data/crashdump_${SLOT_NAME}_${CURT_DTIME}.tar.gz"
LOG_MSG_PREFIX=""

echo "Auto Dump for $SLOT_NAME Started"
logger -t "ipmid" -p daemon.crit "${LOG_MSG_PREFIX}Crashdump for FRU: $SLOT_NUM started"

#HEADER LINE for the dump
echo "Crash Dump generated at $(date)" > "$CRASHDUMP_FILE"

{
  # Get BMC version & hostname
  echo "Get BMC version info: "
  "$FW_UTIL" bmc --version
  uname -a
  cat /etc/issue

  # Get fw info

  echo "Get firmware version info: "
  "$FW_UTIL" "$SLOT_NAME" "--version"

  # Get FRUID info
  echo "Get FRUID Info:"
  "$FRUID_UTIL" "$SLOT_NAME"

  # Sensors & sensor thresholds
  echo "Sensor history at dump:"
  dump_sensor_history "$SLOT_NAME"
  echo "Sensor threshold at dump:"
  dump_sensor_threshold "$SLOT_NAME"

  # MCA dumps
  echo "Crashdump v1.0:"
  cat "$CRASHDUMP_DECODED_FILE"
  echo "================="

  echo "Auto Dump End at $(date)"
} >> "$CRASHDUMP_FILE"

tar zcf "$CRASHDUMP_LOG_ARCHIVE" -C "$(dirname "$CRASHDUMP_FILE")" "$(basename "$CRASHDUMP_FILE")" && \
rm -rf "$CRASHDUMP_DECODED_FILE" && \
rm -rf "$CRASHDUMP_FILE" && \
logger -t "ipmid" -p daemon.crit "${LOG_MSG_PREFIX}Crashdump for FRU: $SLOT_NUM is generated at $CRASHDUMP_LOG_ARCHIVE"
# cp -f "$CRASHDUMP_LOG_ARCHIVE" /tmp

# update crashdump history, only keep last three archive for each slot
update_crashdump_history $SLOT_NUM "$CURT_DTIME"
clear_crashdump_archive $SLOT_NUM

echo "Auto Dump for $SLOT_NAME Completed"

# Remove current pid file
rm "$PID_FILE"

echo "${LOG_MSG_PREFIX}Auto Dump Stored in $CRASHDUMP_LOG_ARCHIVE"
exit 0


#!/bin/sh
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
### BEGIN INIT INFO
# Provides:          setup-emmcd
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Start eMMC monitor daemon
### END INIT INFO

echo "Setup eMMC Daemon.."

CACHE_STORE_DIR="/tmp/cache_store"
EXTCSD_CACHE="${CACHE_STORE_DIR}/mmc0_extcsd"
MMC_DEVICE="/dev/mmcblk0"
MMCRAW_CMD="/usr/local/bin/mmcraw"

if [ ! -b "$MMC_DEVICE" ]; then
  echo "$MMC_DEVICE does not exist. Exiting."
  exit 1
fi

if [ ! -d "$CACHE_STORE_DIR" ]; then
  mkdir -p "$CACHE_STORE_DIR" || exit 1
fi

if ! [[ -f $EXTCSD_CACHE ]]; then
  "$MMCRAW_CMD" read-extcsd "$MMC_DEVICE" > "$EXTCSD_CACHE"
fi

# Display eMMC device summary
EMMC_INFO=$("$MMCRAW_CMD" show-summary "$MMC_DEVICE")
echo "$EMMC_INFO"

if echo "$EMMC_INFO" | grep "Device Health.*Undefined" > /dev/null 2>&1 &&
   echo "$EMMC_INFO" | grep "Life Time.*Undefined" > /dev/null 2>&1; then
    echo "emmcd not started: device life time estimates not supported."
    exit 1
fi

echo "Starting emmcd daemon.."
runsv /etc/sv/emmcd > /dev/null 2>&1 &
exit 0


#!/bin/sh
#
# Copyright 2017-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

exec /usr/local/bin/fru-svcd


#!/bin/sh
#
# Copyright 2017-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          fru-svcd
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: dbus based fru service
### END INIT INFO

echo -n "Setup fru svcd for FBTP... "

runsv /etc/sv/fru-svcd > /dev/null 2>&1 &

echo "done."


#!/bin/sh
# execute <fscd.py> <min syslog level>
# log_level = <debug, warning, info>
# Default log level in fscd is set to warning, if any other level is needed
# set here
exec /usr/bin/fscd.py 'warning'


#!/bin/sh

rm -f ../fscd/*.pyc
rm -rf ./*.pyc
rm -rf ./ply/*.pyc
rm -f ../fscd/parser.out
rm -f ../fscd/parsetab.py

# reset all fan set data
echo 0 > ./test-data/test-util-data/fan0-set-data
echo 0 > ./test-data/test-util-data/fan1-set-data
echo 0 > ./test-data/test-util-data/fan2-set-data
echo 0 > ./test-data/test-util-data/fan3-set-data
echo 0 > ./test-data/test-util-data/fan4-set-data
echo 0 > ./test-data/test-util-data/fan5-set-data
echo 0 > ./test-data/test-sysfs-data/fantray0_pwm
echo 0 > ./test-data/test-sysfs-data/fantray1_pwm
echo 0 > ./test-data/test-sysfs-data/fantray2_pwm
echo 0 > ./test-data/test-sysfs-data/fantray3_pwm
echo 0 > ./test-data/test-sysfs-data/fantray4_pwm
echo 0 > ./test-data/test-sysfs-data/fantray5_pwm
echo 15000 > ./test-data/test-sysfs-data/4-0033/temp1_input
echo 15000 > ./test-data/test-sysfs-data/3-004b/temp1_input
echo 15000 > ./test-data/test-sysfs-data/3-0048/temp1_input


#!/bin/sh

FILE=$1
FAN=$2
cat $FILE | head -n $FAN | tail -n 1


file_name=$1
other=$2
cat ./test-data/test-util-data/$file_name


file_name=$0
pwm_value=$1
pwm_num=$2
echo $pwm_value > ./test-data/test-util-data/fan$pwm_num-set-data


#!/bin/sh
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          setup-healthd
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Setup sensor monitoring
### END INIT INFO

echo -n "Setup healthd for BMC "

runsv /etc/sv/healthd > /dev/null 2>&1 &

echo "done."


#!/bin/bash
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
logger "run-dhc6.sh: dhclient -6 Started.."
pid="/var/run/dhclient6.eth0.pid"
exec dhclient -6 -d -D LL -pf ${pid} eth0 "$@"


#!/bin/bash
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
logger "run-dhc6.sh: dhclient -6 Started.."
pid="/var/run/dhclient6.eth0.pid"

# shellcheck disable=SC2086
mac_to_ll() {
  IFS=':'; set $1; unset IFS
  echo "fe80::$(printf %x $((0x$1 ^ 2)))$2:${3}ff:fe$4:$5$6" | \
    sed -E 's/:0+/:/g; s/:{3,}/::/; s/:$/:0/'
}

exp_ll=
ll=

for _ in {1..30}; do
  # wait getting address from NC-SI
  if [ "$(cat /sys/class/net/eth0/addr_assign_type)" = "3" ]; then
    exp_ll=$(mac_to_ll "$(cat /sys/class/net/eth0/address)")
    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \([^ ]*\)\/.*$/\1/;t;d')
    if [ "$ll" = "$exp_ll" ]; then
      break
    fi
    # re-generate link-local address
    ip -6 addr flush dev eth0 scope link
    echo 1 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode
    echo 0 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode
    break;
  fi
  sleep 1
done

if [ "$ll" != "$exp_ll" ]; then
  for _ in {1..100}; do
    usleep 10000
    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \([^ ]*\)\/.*$/\1/;t;d')
    if [ "$ll" = "$exp_ll" ]; then
      break;
    fi
  done
fi

exec dhclient -6 -d -D LL -pf ${pid} eth0 "$@"


#!/bin/bash
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
logger "run-dhc6.sh: dhclient -6 Started.."
pid="/var/run/dhclient6.eth0.pid"
exec dhclient -6 -d -D LL --address-prefix-len 64 -pf ${pid} eth0 "$@"


#!/bin/bash
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
logger "run-dhc6.sh: dhclient -6 Started.."
pid="/var/run/dhclient6.eth0.pid"

# shellcheck disable=SC2086
mac_to_ll() {
  IFS=':'; set $1; unset IFS
  echo "fe80::$(printf %x $((0x$1 ^ 2)))$2:${3}ff:fe$4:$5$6" | \
    sed -E 's/:0+/:/g; s/:{3,}/::/; s/:$/:0/'
}

exp_ll=
ll=

for _ in {1..30}; do
  # wait getting address from NC-SI
  if [ "$(cat /sys/class/net/eth0/addr_assign_type)" = "3" ]; then
    exp_ll=$(mac_to_ll "$(cat /sys/class/net/eth0/address)")
    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \([^ ]*\)\/.*$/\1/;t;d')
    if [ "$ll" = "$exp_ll" ]; then
      break
    fi
    # re-generate link-local address
    ip -6 addr flush dev eth0 scope link
    echo 1 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode
    echo 0 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode
    break;
  fi
  sleep 1
done

if [ "$ll" != "$exp_ll" ]; then
  for _ in {1..100}; do
    usleep 10000
    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \([^ ]*\)\/.*$/\1/;t;d')
    if [ "$ll" = "$exp_ll" ]; then
      break;
    fi
  done
fi

exec dhclient -6 -d -D LL --address-prefix-len 64 -pf ${pid} eth0 "$@"


#!/bin/bash
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
echo -n "Setup dhclient for IPv6... "
runsv /etc/sv/dhc6 > /dev/null 2>&1 &
echo "done."


#!/bin/bash
### BEGIN INIT INFO
# Provides:          hostname
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Set hostname based on /etc/hostname
### END INIT INFO
HOSTNAME="bmc-oob."

set_hostname() {
  local name=$1
  # Update /etc configuration and persistent cache.
  echo $name > /etc/hostname
  echo $name > /mnt/data/hostname
  # Set hostname
  hostname $name
  # Reload/Restart any services needing the updated hostname
  /etc/init.d/syslog reload
}

if [ -s /mnt/data/hostname ]; then
  # Use the cached copy to set the hostname
  HOSTNAME=$(cat /mnt/data/hostname)
fi
set_hostname $HOSTNAME


#!/bin/sh
#
# Copyright 2014-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          setup-ipmid
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Set IPMI Message handler
### END INIT INFO

echo -n "Setup IPMI message handler... "
runsv /etc/sv/ipmid > /dev/null 2>&1 &
echo "done."


#! /bin/sh
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          kcsd
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:      0 6
# Short-Description: Provides kcs message tx/rx service
#
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
DAEMON=/usr/local/bin/kcsd
NAME=kcsd
DESC="KCS Rx/Tx Daemon"

test -f $DAEMON || exit 0

STOPPER=
ACTION="$1"

case "$ACTION" in
  start)
    echo -n "Starting $DESC: "
    $DAEMON 2 BMC_READY_N > /dev/null 2>&1 &
    $DAEMON 1 BMC_READY_N > /dev/null 2>&1 &
    echo "$NAME."
    ;;
  stop)
    echo -n "Stopping $DESC: "
    start-stop-daemon --stop --quiet --exec $DAEMON
    echo "$NAME."
    ;;
  restart|force-reload)
    echo -n "Restarting $DESC: "
    start-stop-daemon --stop --quiet --exec $DAEMON
    sleep 1
    $DAEMON 2 BMC_READY_N > /dev/null 2>&1 &
    $DAEMON 1 BMC_READY_N > /dev/null 2>&1 &
    echo "$NAME."
    ;;
  status)
    status $DAEMON
    exit $?
    ;;
  *)
    N=${0##*/}
    N=${N#[SK]??}
    echo "Usage: $N {start|stop|status|restart|force-reload}" >&2
    exit 1
    ;;
esac

exit 0


#!/bin/sh

INITD="/etc/init.d"
IF_DIR="/mnt/data/etc/network"
IF_CONF="interfaces"

IF_UPDATE_CONF="$IF_DIR/$IF_CONF"
IF_TARGET_CONF="/etc/network/interfaces"
IF_UP="/etc/network/if-up.d"
IF_DOWN="/etc/network/if-down.d"

SV_PREFIX="/etc/sv/dhc6_"
RUN_SV_PREFIX="runsv $SV_PREFIX"

function init_conf()
{
  if [ ! -d $IF_DIR ];
  then
    mkdir -p $IF_DIR
  fi

  if_name=""
  if [ ! -f $IF_UPDATE_CONF ];
  then
    while IFS='' read -r line || [[ -n "$line" ]];
    do
      if ! [[ $line = \#* ]];
      then
        echo "$line" >> $IF_UPDATE_CONF
        if [[ $line = iface* ]];
        then
          if_name=$(echo $line | awk -F' ' '{print $2}')
          if [[ $if_name = eth* ]];
          then
            echo -e "\niface $if_name inet6 dhcp" >> $IF_UPDATE_CONF
          fi
        fi
      fi
    done < "$IF_TARGET_CONF"
  fi
}

function update_rc5()
{
  out="setup-dhc6_$1.sh"
  echo "#!/bin/sh" >> $out
  echo "echo -n \"Setup the dhclient of $1 for IPv6...\"" >> $out
  echo "$RUN_SV_PREFIX$1 &>/dev/null &" >> $out
  echo "echo \"done.\"" >> $out
  chmod 755 $out
  mv $out $INITD
  update-rc.d -f $out remove &>/dev/null
  update-rc.d $out start 2 5 S . &>/dev/null
}

function update_sv()
{
  folder="$SV_PREFIX$1"
  out="$folder/run"

  if [ ! -d "$folder" ];
  then
    mkdir -p $folder
  fi

  cat /dev/null > $out
  echo "#!/bin/sh" >> $out
  echo "pid=\"/var/run/dhclient6.$1.pid\"" >> $out
  echo "exec dhclient -6 -d -D LL -pf \${pid} $1 \"\$@\"" >> $out
  chmod 755 $out
}

function update_ifupdown()
{
  #up
  out="$IF_UP/dhcpv6_$1_up"
  cat /dev/null > $out
  echo "#!/bin/bash" >> $out
  echo "if [ \"\$IFACE\" == \"$1\" ]; then" >> $out
  echo "  sv status dhc6_$1 &>/dev/null &&\\" >> $out
  echo "  sv restart dhc6_$1" >> $out
  echo "fi" >> $out
  echo "exit 0" >> $out
  chmod 755 $out

  #down
  out="$IF_DOWN/dhcpv6_$1_down"
  cat /dev/null > $out
  echo "#!/bin/bash" >> $out
  echo "if [ \"\$IFACE\" == \"$1\" ]; then" >> $out
  echo "  sv stop dhc6_$1 $> /dev/null &" >> $out
  echo "fi" >> $out
  chmod 755 $out
}

function deploy_setting()
{
  update_rc5 $1
  update_sv $1
  update_ifupdown $1
}

function update_conf()
{
  #clear the old content
  cat /dev/null > $IF_TARGET_CONF

  #Update the new content
  i=0
  vlan_id=""
  record_vlan=""
  while IFS='' read -r line || [[ -n "$line" ]];
  do
    interface=""
    if_family=""
    method=""

    if [[ $line = iface* ]];
    then
      interface=$(echo $line | awk -F' ' '{print $2}')
      if_family=$(echo $line | awk -F' ' '{print $3}')
      method=$(echo $line | awk -F' ' '{print $4}')
      if [ "$record_vlan" == "" ];
      then
        record_vlan=$(echo $interface | awk -F'.' '{print $2}')
      fi

      if ! [[ $interface = lo* ]];
      then
        /sbin/ifconfig $interface 0 > /dev/null 2>&1
      fi
    fi

    if ! [ "$record_vlan" == "$vlan_id" ] && [[ $interface = eth* ]];
    then
      actual_if=$(echo $interface | awk -F'.' '{print $1}')
      /sbin/vconfig add $actual_if $record_vlan
      vlan_id=$record_vlan
    fi

    if [ "$if_family" == "inet6" ] && [ "$method" == "dhcp" ];
    then
      deploy_setting $interface
    else
      if [ "$line" == "" ];
      then
        ((i++))
      else
        i=0
      fi

      if [ $i -lt 2 ];
      then
        echo "$line" >> $IF_TARGET_CONF
      fi
    fi
  done < "$IF_UPDATE_CONF"
}

function clear_dhc6()
{
  SV_PATH="/etc/sv"
  for file in $SV_PATH/*
  do
    if [[ $file = $SV_PATH/dhc6* ]];
    then
      #stop service
      sv_name=$(echo $file | awk -F'/' '{print $4}')
      /usr/bin/sv stop $sv_name $> /dev/null

      #kill runsv id
      sv_id=$(ps | grep "runsv /etc/sv/$sv_name\$" | head -n 1 | awk -F' ' '{print $1}')
      /bin/kill -9 $sv_id > /dev/null 2>&1

      #rm the dir
      rm -rf $file
    fi
  done

  rm -rf $IF_UP/dhcpv6_*
  rm -rf $IF_DOWN/dhcpv6_*
  rm -rf $INITD/setup-dhc6_*
  rm -rf /etc/rc5.d/S02setup-dhc6_*
}

function clear_vlan()
{
  list=$(ip a | grep @ | cut -d ":" -f 2)
  IFS=' '
  for intf in $list;
  do
    if [ "$intf" == "" ];
    then
      continue
    fi

    intf=$(echo $intf | tr -d '\040\011\012\015')

    vintf=$(echo $intf | cut -d "@" -f 1)
    intf=$(echo $intf | cut -d "@" -f 2 | awk '{print tolower($0)}')

    if [ "$intf" == "none" ];
    then
      continue
    fi

    /sbin/vconfig rem $vintf
  done
}

function run_dhc6()
{
  RC5D="/etc/rc5.d"
  for file in $RC5D/*
  do
    if [[ $file = $RC5D/S02setup-dhc6* ]];
    then
      sh $file $> /dev/null
    fi
  done
}

if [ "$1" == "start" ];
then
  init_conf
  update_conf
elif [ "$1" == "restart" ];
then
  /sbin/ifdown -a
  clear_vlan
  clear_dhc6
  init_conf
  update_conf
  /sbin/ifup -a
  run_dhc6
fi


#!/bin/sh

# PLATFORM MAY CHOOSE TO OVERRIDE THIS FILE
echo -n "Starting mTerm console server..."
runsv /etc/sv/mTerm > /dev/null 2>&1 &
echo "done."


#!/bin/sh
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          enable-aen
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Setup sensor monitoring
### END INIT INFO

echo "Enable standard AENs:(Link Status, Config Req, Driver Status)" >> /dev/kmsg
/usr/local/bin/ncsi-util 8 0 0 0 0 0 0 0 7

echo "done."


#!/bin/sh
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          setup-ncsid
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Setup sensor monitoring
### END INIT INFO

echo -n "Setup ncsid for BMC "

runsv /etc/sv/ncsid > /dev/null 2>&1 &

echo "done."


#! /bin/sh
#
# Copyright 2014-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          oob-nic
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:      0 6
# Short-Description: One of the first scripts to be executed. Starts or stops
#               the OOB NIC.
#
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/oob-nic
NAME=oob-nic
DESC="OOB NIC Driver"

# source function library
. /etc/init.d/functions

test -f $DAEMON || exit 0

# enable the isolation buffer
. /usr/local/bin/openbmc-utils.sh

fix_etc_interfaces() {
    local intf_conf board_rev board_type enable_oob
    if wedge_should_enable_oob; then
        intf_conf="/etc/network/interfaces"
        if ! grep oob $intf_conf > /dev/null 2>&1; then
            echo >> $intf_conf
            echo "auto oob" >> $intf_conf
            echo "iface oob inet dhcp" >> $intf_conf
        fi
    fi
}

STOPPER=
ACTION="$1"

case "$ACTION" in
  start)
    echo -n "Starting $DESC: "
    if [ ! -d /dev/net ]
    then
      mkdir /dev/net
    fi
    if [ ! -f /dev/net/tun ]
    then
      mknod /dev/net/tun c 10 200
      chmod 666 /dev/net/tun
    fi
    fix_etc_interfaces
    $DAEMON > /dev/null 2>&1 &
    echo "$NAME."
    ;;
  stop)
    echo -n "Stopping $DESC: "
    start-stop-daemon --stop --quiet --exec $DAEMON
    echo "$NAME."
    ;;
   restart|force-reload)
    echo -n "Restarting $DESC: "
    start-stop-daemon --stop --quiet --exec $DAEMON
    sleep 1
    fix_etc_interfaces
    $DAEMON > /dev/null 2>&1 &
    echo "$NAME."
    ;;
  status)
    status $DAEMON
    exit $?
    ;;
  *)
    N=${0##*/}
    N=${N#[SK]??}
    echo "Usage: $N {start|stop|status|restart|force-reload}" >&2
    exit 1
    ;;
esac

exit 0


#!/bin/sh

echo "*****Running platform-svc HotPlugDetectionMechanism unit tests**********"
/usr/bin/test-platform-svc-hotplugdetectionmechanism

echo "*****Running platform-svc FRU unit tests********************************"
/usr/bin/test-platform-svc-fru

echo "*****Running platform-svc PlatformObjectTree unit tests*****************"
/usr/bin/test-platform-svc-platform-object-tree


#!/bin/sh
(sleep 5; PYTHONPATH=/etc python /etc/rackmon-config.py) &
export RACKMOND_FOREGROUND=1
# Give PSUs 2ms of grace time to let go of the bus after they respond to a
# command
export RACKMOND_MIN_DELAY=2000
exec /usr/local/bin/rackmond


#!/bin/bash
#
# Copyright 2014-present Facebook. All Rights Reserved.
#
### BEGIN INIT INFO
# Provides:          setup-rackmond
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Start Rackmon service
### END INIT INFO

runsv /etc/sv/rackmond > /dev/null 2>&1 &
sv $1 rackmond


#!/bin/sh
# Copyright 2021-present Facebook. All Rights Reserved.
ln -s /etc/aspeed_uart.conf /etc/rackmon.conf
exec /usr/local/bin/rackmond


#!/bin/sh
runsv /etc/sv/redfishevents >/dev/null 2>&1 &
# delay 0.5 seconds to avoid suprising error print like below:
# warning: restapi: can't open supervise/control: No such file or directory
# root casue is runit daemon is not ready.
if [ -n "$1" ]; then
    (sleep 0.5; sv "$1" redfishevents) &
fi


#!/bin/sh
exec /usr/local/bin/sensord SENSORD_LAUNCH_ARGS


#!/bin/sh
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          setup-sensord
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Setup sensor monitoring
### END INIT INFO

echo -n "Setup sensor monitoring... "
runsv /etc/sv/sensord > /dev/null 2>&1 &

echo "done."


#!/bin/bash
#
# Copyright 2014-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

input=$1

print_usage() {

    echo "  slot to host name lookup"
    echo ""
    echo "  Usage:      slot-util [ slot1, slot2, slot3, slot4, all ] : shows host for a particular/all slot(s)"
    echo "              slot-util [ 1, 2, 3, 4 ]                      : shows host for a particular slot"
    echo "              slot-util [ hostname ]                        : shows slot number for a host"
    echo "              slot-util --show-mac                          : shows MAC address assigned for each host"
}

if [ $# -eq 0 ]; then
    print_usage
    exit 1
fi

ocp3nic=0
sku_type=0

if grep -q "yosemite" /etc/issue; then
    sku_type=0
elif grep -q "halfdome" /etc/issue; then
    sku_type=fffd
    ocp3nic=1
elif grep -q "fby35" /etc/issue; then
    sku_type=fffe
    ocp3nic=1
elif grep -q "fby3" /etc/issue; then
    sku_type=ffff
    ocp3nic=1
else
    # fby2 file
    # shellcheck disable=SC1091
    . /usr/local/fbpackages/utils/ast-functions

    # if no get_slot_type exist (such as Yosemite 1), assume 4 server config
    if [ -n "$(LC_ALL=C type -t get_slot_type)" ] && [ "$(LC_ALL=C type -t get_slot_type)" = function ]; then
      for i in $(seq 1 1 4)
      do
        tmp_sku="$(get_slot_type "$i")"
        sku_type="$(($(("$tmp_sku" << $(("$(("$i"*4))" - 4))))+"$sku_type"))"
      done
    fi
    # OCP3 NIC detection
    GPIOCLI_CMD=/usr/local/bin/gpiocli
    prsnt_a=$($GPIOCLI_CMD get-value --shadow MEZZ_PRSNTA2_N | awk -F= '{print $2}')
    prsnt_b=$($GPIOCLI_CMD get-value --shadow MEZZ_PRSNTB2_N | awk -F= '{print $2}')
    if ((prsnt_a == 0 && prsnt_b == 1)); then
      ocp3nic=1
    else
      ocp3nic=0
    fi
fi

# get BMC mac address and conver it to base 10 integer
bmc_mac_dec="$( printf "%d\\n" "0x$(sed s/://g "/sys/class/net/eth0/address")")"

# get neighboring devices in {hostname, MAC} format, shows only entries that can resolve to host name
host_table=$(ip -r neigh show dev eth0 | grep -iE 'com|edu|gov|org' | sort -k 3)

# calculate expected MAC address for each slot, convert it back to hex str
#
# MAC address calculation is different for 2xTL+2x carrier
case "$sku_type" in
   "0")
      if [ $ocp3nic -eq 1 ]; then
        echo "4 server, OCP3 NIC"
        slot1_mac=$(printf "%012x\\n" $((bmc_mac_dec-4)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
        slot2_mac=$(printf "%012x\\n" $((bmc_mac_dec-3)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
        slot3_mac=$(printf "%012x\\n" $((bmc_mac_dec-2)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
        slot4_mac=$(printf "%012x\\n" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//');
      else
        echo "4 server, OCP2 NIC"
        slot1_mac=$(printf "%012x\\n" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
        slot2_mac=$(printf "%012x\\n" $((bmc_mac_dec+1)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
        slot3_mac=$(printf "%012x\\n" $((bmc_mac_dec+3)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
        slot4_mac=$(printf "%012x\\n" $((bmc_mac_dec+5)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
      fi
   ;;
   "fffd")
      echo "Half Dome, OCP3 NIC"
      slot1_mac=$(printf "%012x\\n" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
      slot3_mac=$(printf "%012x\\n" $((bmc_mac_dec+1)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
   ;;
   "fffe")
      echo "Yosemite V3.5, OCP3 NIC"
      slot1_mac=$(printf "%012x\\n" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
      slot2_mac=$(printf "%012x\\n" $((bmc_mac_dec+1)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
      slot3_mac=$(printf "%012x\\n" $((bmc_mac_dec+3)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
      slot4_mac=$(printf "%012x\\n" $((bmc_mac_dec+5)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
   ;;
   "ffff")
      echo "Yosemite V3, OCP3 NIC"
      slot1_mac=$(printf "%012x\\n" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
      slot2_mac=$(printf "%012x\\n" $((bmc_mac_dec+1)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
      slot3_mac=$(printf "%012x\\n" $((bmc_mac_dec+3)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
      slot4_mac=$(printf "%012x\\n" $((bmc_mac_dec+5)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
   ;;
   "1028")
      echo "2server + 2GPv2, OCP2 NIC"
      slot2_mac=$(printf "%012x\\n" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
      slot4_mac=$(printf "%012x\\n" $((bmc_mac_dec+1)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
   ;;
   *)
      echo "unknown config - use default"
      slot1_mac=$(printf "%012x\\n" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
      slot2_mac=$(printf "%012x\\n" $((bmc_mac_dec+1)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
      slot3_mac=$(printf "%012x\\n" $((bmc_mac_dec+3)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
      slot4_mac=$(printf "%012x\\n" $((bmc_mac_dec+5)) | sed -e 's/[0-9A-Fa-f]\{2\}/&:/g' -e 's/:$//')
   ;;
esac

if [ "$1" == "--show-mac" ]; then
  for i in 1 2 3 4
  do
    slotmac="slot$i"
    slotmac="${slotmac}_mac"
    eval echo slot$i MAC: "${!slotmac}"
  done
  exit 1
fi

# match host name to each slot based on MAC address
if [[ -n $slot1_mac ]]; then
  # shellcheck disable=SC2034
  host1="$(echo "$host_table" | grep -i "${slot1_mac}" | cut  -d " " -f1)"
fi
if [[ -n $slot2_mac ]]; then
  # shellcheck disable=SC2034
  host2="$(echo "$host_table" | grep -i "${slot2_mac}" | cut  -d " " -f1)"
fi
if [[ -n $slot3_mac ]]; then
  # shellcheck disable=SC2034
  host3="$(echo "$host_table" | grep -i "${slot3_mac}" | cut  -d " " -f1)"
fi
if [[ -n $slot4_mac ]]; then
  # shellcheck disable=SC2034
  host4="$(echo "$host_table" | grep -i "${slot4_mac}" | cut  -d " " -f1)"
fi

# check if user asked for a specific slot, either in "slotX", or just "X"
if [[ "$input" =~ ^[0-9]+$ ]]; then
    slot_num=$input
elif [[ $1 == "slot"* ]]; then
    slot_num=$(echo "$1" | tr -dc '0-9')
fi

# check if user specified "all" option
if [ -z "$slot_num" ]; then
    if [[ $1 == "all" ]]; then
        for i in 1 2 3 4
        do
           eval echo slot$i: \$host$i
        done
    else
        # check if user entered a valid host name
        match=$(echo "$host_table" | grep -i "$1")
        # if no match
        if [ -z "$match" ]; then
            echo host name "$1" not found
        else
            for i in 1 2 3 4
            do
               hostname=$( (eval echo \$host$i) | grep -i "$1")
               if [ -z "$hostname" ]; then
                   :
               else
                   eval echo slot$i: \$host$i
               fi
            done
        fi
    fi
else
    # user specified a specific slot
    eval echo slot"$slot_num": \$host"$slot_num"
fi


#!/bin/bash
HOSTNAME="bmc-oob."

set_hostname() {
  local name=$1
  # Update /etc configuration and persistent cache.
  echo "$name" > /etc/hostname
  echo "$name" > /mnt/data/hostname
  # Set hostname
  hostname "$name"
}

if [ -s /mnt/data/hostname ]; then
  # Use the cached copy to set the hostname
  HOSTNAME="$(cat /mnt/data/hostname)"
fi

set_hostname "$HOSTNAME"


#!/bin/sh
#
# Copyright 2004-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
usage() {
    echo "Usage: $0 <on | off>" >&2
}

set -e

if [ "$#" -ne 1 ]; then
    usage
    exit 1
fi

case "$1" in
"on")
    echo "Enabling watchdog. Note: this does not start the watchdog!"
    echo "x" > /dev/watchdog
    ;;
"off")
    echo "Disabling watchdog."
    echo "X" > /dev/watchdog
    ;;
*)
    usage
    exit 1
    ;;
esac


#!/usr/bin/bash

rm -rf gen/com
sdbus++-gen-meson \
    --command meson \
    --directory yaml \
    --output gen


#!/bin/bash

iteration=4100
for ((i=1;i<iteration;i=i*2));
do
  python service-memorytest.py --i $i &
  spid=$(echo $!)
  python ipc-memorytest.py --i $i &
  ipid=$(echo $!)

  # wait for the connection to service to be set up
  python caller-memorytest.py

  echo $i routes: $(top -b -n 1 | grep Mem)
  kill $spid $ipid
done


#!/bin/bash
eval `dbus-launch --auto-syntax`
dbuspid=$(ps | grep dbus | grep fork | grep -o "^ *[0-9]*")
./dbus-testserver &
serverpid=$(ps | grep dbus-testserver | grep -o "^ *[0-9]*")

iteration=1000
for ((i=0;i<iteration;i++));
do
  dbus-send --session --type=method_call \
            --dest=org.openbmc.TestServer \
            /org/openbmc/test \
            org.openbmc.TestInterface.HelloWorld \
            string:'greeting'
done
kill $serverpid
kill $dbuspid


#!/bin/bash
eval `dbus-launch --auto-syntax`
dbuspid=$(ps | grep dbus | grep fork | grep -o "^ *[0-9]*")
./dbus-testserver &
serverpid=$(ps | grep dbus-testserver | grep -o "^ *[0-9]*")

./dbus-latencytest

kill $serverpid
kill $dbuspid


#!/bin/bash

eval `dbus-launch --auto-syntax`
iteration=4100
for ((i=1;i<iteration;i=i*2));
do
  dbuspid=$(ps | grep dbus | grep fork | grep -o "^ *[0-9]*")
  ./dbus-mem-testserver $i &
  serverpid=$(echo $!)

  sleep 1
  echo $i objects: $(top -b -n 1 | grep Mem)
  kill $serverpid
done
kill $dbuspid


#!/bin/bash
eval `dbus-launch --auto-syntax`
dbuspid=$(ps | grep dbus | grep fork | grep -o "^ *[0-9]*")
./dbus-interface-test &
serverpid=$(ps | grep dbus-interface-test | grep -o "^ *[0-9]*")

sleep 1

dbus-send --session --type=method_call --print-reply \
          --dest=org.openbmc.TestServer \
            /org/openbmc/test \
            org.openbmc.TestInterface.Ping

kill $serverpid
kill $dbuspid


#!/bin/sh
#
# Copyright 2014-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          setup-rest-api
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Set REST API handler
### END INIT INFO

runsv /etc/sv/restapi >/dev/null 2>&1 &
# delay 0.5 seconds to avoid suprising error print like below:
# warning: restapi: can't open supervise/control: No such file or directory
# root casue is runit daemon is not ready.
if [ -n "$1" ]; then
    (sleep 0.5; sv "$1" restapi) &
fi


#!/bin/bash
# Copyright 2014-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA

# Sets up the bootargs so that we can boot with the desired chips
# exposed.

set -xeu -o pipefail

if grep -q wedge100 /etc/issue
then
    openbmc_gpio_util.py config ROMCS1#
fi

# If verified boot mount flash1rw as well
if [ -f /usr/local/bin/vboot-util ]
then
    if grep -q rom /proc/mtd
    then
        echo "Verified boot"
        EXTRA_BOOTARGS="mtdparts=spi0.0:32M@0x0(flash0),0x20000@0x60000(env);spi0.1:32M@0x0(flash1),0x01ff0000@0x10000(flash1rw) dual_flash=1"
    else
        echo "Verified boot detected, but no ROM found"
        exit 1
    fi
else
    echo "Non-verified boot"
    EXTRA_BOOTARGS="mtdparts=spi0.0:32M@0x0(flash0),0x20000@0x60000(env);spi0.1:-(flash1) dual_flash=1";
fi

bootargs=$(fw_printenv bootargs|sed 's/bootargs=//')
if grep -q mtdparts= <<<"$bootargs"
then
    echo "Bootargs already applied."
    exit 0
fi

bootargs="${bootargs} ${EXTRA_BOOTARGS}"

fw_setenv bootargs "${bootargs}"

echo "All set. Now go ahead and reboot!"


#!/bin/bash
# Selects the primary chip and re-flashes it with the image URL given
# as an argument, or with the default one from yum.

set -xeuo pipefail

platform=$(awk '{print $NF}' /etc/issue|cut -d- -f1)

function default_url() {
    echo "http://yum/fbpkg/openbmc.image.${platform}:DEFAULT"
}

url=${1:-$(default_url)}

if [ "${platform}" = "wedge100" ]
then
    openbmc_gpio_util.py config ROMCS1#
fi

devmem 0x1e785034 32 0x1

dev=$(awk -F: '/"flash0"/{print $1}' /proc/mtd)

wget "$url" -O image

flashcp image "/dev/${dev}"

echo "All flashed to a safe version! Now reboot"


#!/bin/sh

### BEGIN INIT INFO
# Provides:		tcsd trousers
# Required-Start:	$local_fs $remote_fs $network
# Required-Stop:	$local_fs $remote_fs $network
# Should-Start:
# Should-Stop:
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	starts tcsd
# Description:		tcsd belongs to the TrouSerS TCG Software Stack
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/tcsd
NAME=tcsd
DESC="Trusted Computing daemon"
USER="root"

test -x "${DAEMON}" || exit 0

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

case "${1}" in
	start)
		echo "Starting $DESC: "

    # If TPM chip has not been discovered, probe the chip here
		if [ ! -e /dev/tpm* ]
		then
      # Pulse resetting TPM can sometimes (rarely) cause
      # COMe CPU to hang, if the reset sequence is performed while
      # X86 CPU (BIOS or Kernel) is talking to TPM. So we don't
      # pulse reset TPM here, but just turn it "on". (active low signal)
      echo 1 > /sys/bus/i2c/drivers/syscpld/12-0031/tpm_lpc_rst_n
      echo 1 > /sys/bus/i2c/drivers/syscpld/12-0031/tpm_spi_rst_n
      # Depending on the previous state, TPM might have been in reset,
      # so we give it enough time after waking up, so that its crypto
      # stuff will initialize, and the chip becomes ready to access.
      sleep 7
      # Finally, register the device and install the driver
      . /usr/local/bin/openbmc-utils.sh
      i2c_device_add 9 0x20 tpm_i2c_infineon
    fi

    # Additionally, Generate symlink to tpm0 or tpm1, so that tcsd can use it
    rm -f /dev/tpm
		if [ -e /dev/tpm0 ]
    then
      ln -s /dev/tpm0 /dev/tpm
    else
      ln -s /dev/tpm1 /dev/tpm
    fi

		start-stop-daemon --start --quiet --oknodo --pidfile /var/run/${NAME}.pid --user ${USER} --chuid ${USER} --exec ${DAEMON} -- ${DAEMON_OPTS}
		RETVAL="$?"
		echo "$NAME."
		[ "$RETVAL" = 0 ] && pidof $DAEMON > /var/run/${NAME}.pid
		exit $RETVAL
		;;

	stop)
		echo "Stopping $DESC: "

		start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/${NAME}.pid --user ${USER} --exec ${DAEMON}
		RETVAL="$?"
                echo  "$NAME."
		rm -f /var/run/${NAME}.pid
		exit $RETVAL
		;;

	restart|force-reload)
		"${0}" stop
		sleep 1
		"${0}" start
		exit $?
		;;
	*)
		echo "Usage: ${NAME} {start|stop|restart|force-reload|status}" >&2
		exit 3
		;;
esac

exit 0


#!/bin/bash
#
# Copyright 2015-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA

# Store and Clear POR bit
store_clear_por() {
  if [ -f /tmp/ast_por ]; then
    return
  fi

  soc_model=$(cat /etc/soc_model 2>/dev/null)

  # default AST G4/G5
  system_reset_reg="0x1e6e203c"
  if [ "$soc_model" = "SOC_MODEL_ASPEED_G6" ]; then
      system_reset_reg="0x1e6e2074"
  fi

  # Read the SRST Rest Flag
  val=$(devmem "$system_reset_reg" 2>/dev/null)
  if [[ "$((val & 0x1))" == "1" ]]; then
      # Power ON Reset
      echo 1 > /tmp/ast_por
  else
      echo 0 > /tmp/ast_por
  fi

  # Clear Power On Reset bit
  devmem "$system_reset_reg" 32 0x1 2>/dev/null
}

# Check to see if BMC power-on-reset
is_bmc_por() {
  store_clear_por
  /bin/cat /tmp/ast_por
}


#!/bin/sh
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA

set -eu -o pipefail

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin

if [ $# -ne 2 ]; then
    echo "Error: invalid command line arguments!"
    echo "Usage: $0 <block-device> <mount-point>"
    exit 1
fi
BLK_DEVICE=$1
MOUNT_POINT=$2

if mount | grep "$BLK_DEVICE"; then
    echo "$BLK_DEVICE is already mounted. Exiting."
    exit 0
fi

SUPPORTED_FS_TYPE="btrfs"

mount_btrfs() {

    #
    # Use blkid to find the underlying filesystem type.
    #
    FS_TYPE="$(blkid "$BLK_DEVICE" || echo 'TYPE="unknown"')"
    FS_TYPE="$(echo "$FS_TYPE" | sed 's/.*TYPE="\([^"]*\).*/\1/')"

    #
    # If filesystem is not btrfs already, convert or reformat.
    #
    case "$FS_TYPE" in
        ext4)
            echo "EXT4 filesystem found on $BLK_DEVICE.  Reformat as btrfs.."
            if ! output="$(mkfs.btrfs -f "$BLK_DEVICE" 2>&1)"; then
                echo "Error: failed to format as btrfs on $BLK_DEVICE:"
                echo "$output"
                exit 1
            fi
            ;;

        btrfs)
            ;;

        *)
            echo "No filesystem found on $BLK_DEVICE. Creating btrfs fs.."
            if ! output=$(mkfs.btrfs -f "$BLK_DEVICE" 2>&1); then
                echo "Error: failed to create btrfs on $BLK_DEVICE:"
                echo "$output"
                exit 1
            fi
            ;;
    esac

    #
    # Run btrfs-check (same as btrfsck) to confirm filesystem integrity.
    #
    if ! output="$(btrfs check "$BLK_DEVICE" 2>&1)"; then
        echo "Error: btrfs volume shows errors:"
        echo "$output"
        echo "Try to repair btrfs"
        if ! output="$(btrfs check --repair "$BLK_DEVICE" 2>&1)"; then
            echo "Error: btrfs volume shows errors:"
            echo "$output"
            exit 1
        fi
    fi

    #
    # Mount btrfs.
    #   Use zstd compression because we get faster speed and less wear.
    #
    echo "Mounting $BLK_DEVICE to $MOUNT_POINT.."
    if ! output=$(mount -o compress=zstd,discard "$BLK_DEVICE" "$MOUNT_POINT" 2>&1);
    then
        echo "Error: failed to mount $BLK_DEVICE to $MOUNT_POINT:"
        echo "$output"
        exit 1
    fi

    #
    # Mount successful.  Show some usage statstics.
    #
    echo "$MOUNT_POINT mounted successfully, device usage:"
    df -h "$MOUNT_POINT"
    btrfs filesystem df "$MOUNT_POINT"
    exit 0
}

mount_ext4() {

    #
    # Workaround for EMMC data lost because sometimes e2fsck detect filesystem fails
    # if SDHCI IO fails when system boot up, add retry to avoid EMMC format by mistake.
    #
    maxtry=3
    retry=0
    while [ $retry -lt $maxtry ]; do
        if ! e2fsck -p "$BLK_DEVICE" > /dev/null 2>&1; then
            retry=$((retry + 1))
            echo "No filesystem found on $BLK_DEVICE try: $retry."
        else
            break
        fi
    done

    #
    # Create ext4 if ext filesystem is not detected or corrupted.
    #
    if [ $retry -eq $maxtry ]; then
        echo "No filesystem found on $BLK_DEVICE after $maxtry times try. Creating ext4 filesystem.."
        if ! output=$(mkfs.ext4 -F "$BLK_DEVICE" 2>&1); then
            echo "Error: failed to create ext4 on $BLK_DEVICE:"
            echo "$output"
            exit 1
        fi
    fi

    #
    # Mount block device to specified mount point.
    #
    echo "Mounting $BLK_DEVICE to $MOUNT_POINT.."
    if ! output=$(mount "$BLK_DEVICE" "$MOUNT_POINT" 2>&1); then
        echo "Error: failed to mount $BLK_DEVICE to $MOUNT_POINT:"
        echo "$output"
        exit 1
    fi

    #
    # Dump summary information.
    #
    echo "$BLK_DEVICE mounted successfully, device usage:"
    df -h "$BLK_DEVICE"
    exit 0
}

mount_$SUPPORTED_FS_TYPE


#!/bin/bash

ubifs_mount() {
    ubi_vol="$1"
    mnt_point="$2"

    echo "ubifs_mount $ubi_vol to $mnt_point.."
    mount -t ubifs "$ubi_vol" "$mnt_point" -o sync,compr=zstd
}

ubifs_resize() {
    ubi_dev="$1"
    vol_id="$2"
    ubi_vol="${ubi_dev}_${vol_id}"
    mnt_point="$3"
    backup_dir="/tmp/mnt_data_ubifs_backup"
    ubi_dev_avali_leb=$(ubinfo "$ubi_dev" | grep "available logical eraseblocks" | awk -F':' '{print $2}' | awk '{print $1}')
    ubi_vol_leb=$(ubinfo "$ubi_vol" | grep "Size" | awk -F':' '{print $2}' | awk '{print $1}')
    new_vol_leb=$((ubi_dev_avali_leb+ubi_vol_leb))

    echo "available leb:    $ubi_dev_avali_leb"
    echo "volume leb:       $ubi_vol_leb"

    if [ "$ubi_dev_avali_leb" -eq 0 ]; then
        # no more avaliable LEBs
        echo "no more avaliable LEBs"
        return 0
    fi

    if ! /bin/mountpoint "$mnt_point"; then
        echo "$mnt_point is not a correct mount point"
        return 1
    fi

    # prepare backup data folder
    if [ -e "$backup_dir" ]; then
        echo "backup folder already exist, please move it to safe place"
        echo "backup folder: $backup_dir"
        return 1
    fi
    cp -ar "$mnt_point" "$backup_dir"

    # umount mount point
    if ! umount "$mnt_point"; then
        rm -rf "$backup_dir"
        echo "umount $mnt_point failed"
        return 1
    fi

    # do resize
    if ! ubirsvol "$ubi_dev" -n "$vol_id" -S "$new_vol_leb"; then
        echo "ubifs volume resize failed (ubirsvol), err_code: $?"
    elif ! mkfs.ubifs -y -r "$backup_dir" "$ubi_vol"; then
        echo "ubifs volume resize failed (mkfs.ubifs), err_code: $?"
    elif ! ubifs_mount "$ubi_vol" "$mnt_point"; then
        echo "ubifs volume resize failed (ubifs_mount), err_code: $?"
    else
        # resize done
        echo "ubifs volume resize done, vol: $ubi_vol, origin LEBs: $ubi_vol_leb, new LEBs: $new_vol_leb"
        rm -rf "$backup_dir"
        return 0
    fi

    # undo resize
    if ! ubirsvol "$ubi_dev" -n "$vol_id" -S "$ubi_vol_leb"; then
        echo "ubifs volume undo resize failed (ubirsvol), err_code: $?"
    elif ! mkfs.ubifs -y -r "$backup_dir" "$ubi_vol"; then
        echo "ubifs volume undo resize failed (mkfs.ubifs), err_code: $?"
    elif ! ubifs_mount "$ubi_vol" "$mnt_point"; then
        echo "ubifs volume undo resize failed (ubifs_mount), err_code: $?"
    else
        # undo resize done
        echo "ubifs volume undo resize done, vol: $ubi_vol, LEBs: $ubi_vol_leb"
        rm -rf "$backup_dir"
        return 0
    fi

    # undo reise failed
    echo "undo resize failed, backup folder: $backup_dir"
    return 1
}

/usr/bin/killall rsyslogd

ubifs_resize /dev/ubi0 0 /mnt/data
ret_val=$?

/usr/sbin/rsyslogd
exit $ret_val


#!/bin/sh
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA

set -eu -o pipefail

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin

if [ $# -ne 1 ]; then
    echo "Error: invalid command line arguments!"
    echo "Usage: $0 <mount-point>"
    exit 1
fi
MOUNT_POINT=$1
MMC_DEVICE="/dev/mmcblk0"
MOUNT_SCRIPT="/usr/local/bin/blkdev_mount.sh"

#
# We provide people a way to disable/skip the script by setting u-boot
# environment variable, and it's mainly intended for cases when something
# is wrong with emmc driver/device.
#
emmc_mount_precheck() {
    lock_dir="/run/lock"
    link_path="/var/lock"

    #
    # the script may be triggered when "/var/lock" is not populated, so
    # let's manually create the directories to avoid fw_printenv failure
    # when creating "/var/lock/fw_printenv.lock".
    #
    if [ ! -d "$lock_dir" ]; then
        if ! output=$(mkdir -p "$lock_dir"); then
            echo "Error: failed to create $lock_dir:"
            echo "$output"
            exit 1
        fi
    fi
    if [ ! -L "$link_path" ]; then
        if ! output=$(ln -s "$lock_dir" "$link_path"); then
            echo "Error: failed to create symlink $link_path:"
            echo "$output"
            exit 1
        fi
    fi

    if fw_printenv | grep "emmc_auto_mount=no" > /dev/null 2>&1; then
        echo "emmc_auto_mount is disabled by uboot env. Skip emmc mount."
        exit 0
    fi

    if [ "x$(kv get emmc_auto_mount persistent || true)" = "xno" ]; then
        echo "emmc_auto_mount is disabled by persistent kv. Skip emmc mount."
        exit 0
    fi

    if [ "x$(kv get emmc_auto_mount || true)" = "xno" ]; then
        echo "emmc_auto_mount is disabled by temporary kv. Skip emmc mount."
        exit 0
    fi
}

emmc_mount_precheck

#
# timeout "-t" option is removed since Busybox version v1.30.0, so we
# need to get rid of "-t" from all yocto-warrior platforms (Busybox
# v1.30.1), but the option is still needed for all yocto-rocko platforms
# (without Busybox v1.24.1).
# MOUNT_SCRIPT takes ~25 seconds if ext4 filesystem needs to be created,
# so 60 seconds timeout value is long enough.
#
MOUNT_TIMEOUT=60
if timeout --help 2>&1 | grep "Usage:.*\[\-t " > /dev/null 2>&1; then
    timeout -t "$MOUNT_TIMEOUT" "$MOUNT_SCRIPT" "$MMC_DEVICE" "$MOUNT_POINT"
else
    timeout "$MOUNT_TIMEOUT" "$MOUNT_SCRIPT" "$MMC_DEVICE" "$MOUNT_POINT"
fi

# Create the rsyslog directory, in case it doesn't exist.
mkdir -p "$MOUNT_POINT/log"


#!/bin/sh
#
# Copyright 2020-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin

show_usage() {
  echo "Error  : invalid command line arguments!"
  echo "Usage  : $0 <mmc_device>"
  echo "Example: $0 /dev/mmcblk0"
  exit -1
}
if [[ $# -ne 1 ]] || ! [[ -e $1 ]]; then
  show_usage
fi
MMC_DEVICE=$1

umount /mnt/data1 > /dev/null

emmc_config_extcsd() {
  # Configure pSLC mode
  vendor=$(mmc cid read /sys/class/mmc_host/mmc0/mmc0\:0001/ | grep manufacturer | cut -d " " -f 2)
  if [[ "$vendor" = "'Micron'" ]]; then
    # Refer Micron document TN-FC-40
    val=$(mmc extcsd read $MMC_DEVICE | grep PARTITIONING_SUPPORT)
    val=${val:0-4}
    partitioning_sup=$((val%2))
    enhanced_sup=$((val/2%2))
    if [[ "$partitioning_sup" != "1" ]] || [[ "$enhanced_sup" != "1" ]]; then
      echo "This eMMC don't support partitioning."
      return
    fi

    completed=$(mmc extcsd read $MMC_DEVICE | grep PARTITION_SETTING_COMPLETED)
    completed=${completed:0-4}
    if [[ "$completed" == "0x01" ]]; then
      echo "Partitioning had been done"
      exit 0
    fi
    echo "Configure eMMC partitions"
    # Set ERASE_GROUP_DEF to 1
    mmcraw -o 175 -D 0x1 write-extcsd $MMC_DEVICE > /dev/null
    # Set ENH_START_ADDR to 0
    mmcraw -o 136 -D 0x0 write-extcsd $MMC_DEVICE > /dev/null
    mmcraw -o 137 -D 0x0 write-extcsd $MMC_DEVICE > /dev/null
    mmcraw -o 138 -D 0x0 write-extcsd $MMC_DEVICE > /dev/null
    mmcraw -o 139 -D 0x0 write-extcsd $MMC_DEVICE > /dev/null
    # Set ENH_SIZE_MULT to MAX_ENH_SIZE_MULT
    max_enh_size_mult=$(mmc extcsd read $MMC_DEVICE | grep MAX_ENH_SIZE_MULT)
    max_enh_size_mult0=0x${max_enh_size_mult:0-2}
    max_enh_size_mult1=0x${max_enh_size_mult:0-4:2}
    max_enh_size_mult2=0x${max_enh_size_mult:0-6:2}
    mmcraw -o 140 -D $max_enh_size_mult0 write-extcsd $MMC_DEVICE > /dev/null
    mmcraw -o 141 -D $max_enh_size_mult1 write-extcsd $MMC_DEVICE > /dev/null
    mmcraw -o 142 -D $max_enh_size_mult2 write-extcsd $MMC_DEVICE > /dev/null
    # Set ENH_USR to 1
    mmcraw -o 156 -D 0x1 write-extcsd $MMC_DEVICE > /dev/null
    # Set PARTITIONING_SETTING_COMPLETED to 1
    mmcraw -o 155 -D 0x1 write-extcsd $MMC_DEVICE > /dev/null
  else
    echo "The manufacturer $vendor is not supported"
  fi
  # Disable cache
  cache_ctl=$(mmc extcsd read $MMC_DEVICE | grep CACHE_CTRL)
  cache_ctl=${cache_ctl:0-4}
  if [[ $cache == "0x01" ]]; then
    echo "Disable eMMC cache"
    mmc cache disable > /dev/null
  fi
}
emmc_config_extcsd

echo "WARNING: Do chassis cycle to apply the enhancement"


#!/bin/bash
#
# Copyright 2014-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#

### BEGIN INIT INFO
# Provides:          eth0_mac_fixup.sh
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description:  Fixup the MAC address for eth0 based on wedge EEPROM
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin

#shellcheck disable=SC1091
source /usr/local/bin/openbmc-utils.sh

# get the MAC from EEPROM
if [ "$(LC_ALL=C type -t bmc_mac_addr)" = function ]; then
    mac=$(bmc_mac_addr)
else
    mac=$(weutil  | grep '^Local MAC' | cut -d' ' -f3)
fi

# get the MAC from u-boot environment
ethaddr=$(fw_printenv | grep "^ethaddr=" | cut -d'=' -f2)

if [ -z "$mac" ]; then
    if [ -n "$ethaddr" ]; then
        # no MAC from EEPROM, use the one from u-boot environment
        echo "No MAC address from EEPROM: use $ethaddr from uboot-env"
        mac="$ethaddr"
    else
        echo "Error: unable to read MAC address from EEPROM or uboot-env!"
        exit 1
    fi
fi

if [ "$ethaddr" != "$mac" ]; then
    # set the MAC from EEPROM back to u-boot environment so that
    # u-boot can use it
    fw_setenv "ethaddr" "$mac"
fi

#ifconfig eth0 hw ether $macifconfig
echo "Update BMC eth0 MAC address to $mac"
ip link set dev eth0 address "$mac"
exit $?


# Copyright 2021-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA

#
# The file contains helper functions to parse flashrom output.
#
# Sample flashrom command output:
#
#   root@bmc:~# flashrom -p linux_spi:dev=/dev/spidev1.0
#   flashrom v1.0 on Linux 5.10.5-minipack (armv6l)
#   flashrom is free software, get the source code at https://flashrom.org
#
#   Using clock_gettime for delay loops (clk_id: 1, resolution: 1ns).
#   Found Winbond flash chip "W25Q128.V" (16384 kB, SPI) on linux_spi.
#   No operations were specified.
#

#
# Generate spidev device name in <spidev#.#> format.
#
# $1 - spi bus number
# $2 - spi device address
#
flash_device_name() {
    echo "spidev${1}.${2}"
}

#
# Wrapper function to launch flashrom command.
#
# $1 - spi device name in "spidev#.#" format. For example, "spidev1.0".
# $@ - extra options passed to flashrom command
#
flashrom_cmd() {
    spi_dev="$1"
    shift

    flashrom -p linux_spi:dev=/dev/"$spi_dev" $@
}

#
# Dump flash summary by running flashrom.
#
# $1 - spi device name in "spidev#.#" format. For example, "spidev1.0".
#
flash_dump_summary() {
    flashrom_cmd "$1"
}

#
# Extract flash information from flashrom output.
#
# $1 - spi device name in "spidev#.#" format. For example, "spidev1.0".
#
flash_extract_info() {
    summary=$(flash_dump_summary "$1")
    info=$(echo "$summary" | grep -E "Found.*flash.*linux_spi")
    if [ -z "$info" ]; then
        echo "Unable to extract flash info! flashrom output:"
        echo "$summary"
        return 1
    fi

    echo "$info"
}

#
# Read flash vendor from flashrom output.
#
# $1 - spi device name in "spidev#.#" format. For example, "spidev1.0".
#
flash_get_vendor() {
    if ! info=$(flash_extract_info "$1"); then
        return 1
    fi

    vendor=$(echo "$info" | cut -d ' ' -f 2)
    if [ -z "$vendor" ]; then
        echo "Unable to determine flash vendor! flashrom output:"
        flash_dump_summary "$1"
        return 1
    fi

    echo "$vendor"
}

#
# Read flash model from flashrom output.
#
# $1 - spi device name in "spidev#.#" format. For example, "spidev1.0".
#
flash_get_model() {
    if ! info=$(flash_extract_info "$1"); then
        return 1
    fi

    model=$(echo "$info" | cut -d '"' -f 2)
    if [ -z "$model" ]; then
        echo "Unable to determine flash model! flashrom output:"
        flash_dump_summary "$1"
        return 1
    fi

    echo "$model"
}

#
# Helper function to check if given input is a decimal number.
#
# $1 - decimal number.
#
is_decimal() {
    echo "$size" | grep -E -q '^[0-9]+$' > /dev/null 2>&1
}

#
# Read flash size from flashrom output (unit: kb).
#
# $1 - spi device name in "spidev#.#" format. For example, "spidev1.0".
#
flash_get_size() {
    if ! info=$(flash_extract_info "$1"); then
        return 1
    fi

    size=$(echo "$info" | cut -d '(' -f 2 | cut -d ' ' -f 1)
    if ! is_decimal "$size"; then
        echo "Unable to determine flash size! flashrom output:"
        flash_dump_summary "$1"
        return 1
    fi

    echo "$size"
}

#
# Read the flash ($1) and store content in the given file ($2).
#
# $1 - spi device name in "spidev#.#" format. For example, "spidev1.0".
# $2 - file name/path to store the flash content.
# $3 - flash model, optional.
#
flash_read() {
    spi_dev="$1"
    image_file="$2"

    if [ -n "$3" ]; then
        model="$3"
    else
        if ! model=$(flash_get_model "$spi_dev"); then
            return 1
        fi
    fi

    flashrom_cmd "$spi_dev" -r "$image_file" -c "$model"
}

#
# Write the file ($2) to the given flash ($1).
#
# $1 - spi device name in "spidev#.#" format. For example, "spidev1.0".
# $2 - file name/path containing the flash image.
# $3 - flash model, optional.
#
flash_write() {
    spi_dev="$1"
    image_file="$2"

    if [ ! -e "$image_file" ]; then
        echo "Error: image file $image_file does not exist!"
        return 1
    fi

    if [ -n "$3" ]; then
        model="$3"
    else
        if ! model=$(flash_get_model "$spi_dev"); then
            return 1
        fi
    fi

    flashrom_cmd "$spi_dev" -w "$image_file" -c "$model"
}

#
# Erase the given flash ($1).
#
# $1 - spi device name in "spidev#.#" format. For example, "spidev1.0".
# $3 - flash model, optional.
#
flash_erase() {
    spi_dev="$1"

    if [ -n "$2" ]; then
        model="$2"
    else
        if ! model=$(flash_get_model "$spi_dev"); then
            return 1
        fi
    fi

    flashrom_cmd "$spi_dev" -E -c "$model"
}