#!/bin/bash
# Copyright VyOS maintainers and contributors <maintainers@vyos.io>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# 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, see <http://www.gnu.org/licenses/>.

. /lib/lsb/init-functions

: ${vyatta_env:=/etc/default/vyatta}
source $vyatta_env

declare progname=${0##*/}
declare action=$1; shift

declare -x LEGACY_BOOTFILE=$vyatta_sysconfdir/config/config.boot
declare -x BOOTFILE=/run/carrier-router/config-db.boot
declare -x DEFAULT_BOOTFILE=$vyatta_sysconfdir/config.boot.default

declare -x VYCONF_CONFIG_DIR=/usr/libexec/vyos/vyconf/config

# If vyos-config= boot option is present, use that file instead
for x in $(cat /proc/cmdline); do
    [[ $x = vyos-config=* ]] || continue
    VYOS_CONFIG="${x#vyos-config=}"
done

if [ ! -z "$VYOS_CONFIG" ]; then
    if [ -r "$VYOS_CONFIG" ]; then
        echo "Config selected manually: $VYOS_CONFIG"
        declare -x BOOTFILE="$VYOS_CONFIG"
    else
        echo "WARNING: Could not read selected config file, using default!"
    fi
fi

declare -a subinit
declare -a all_subinits=( firewall )

if [ $# -gt 0 ] ; then
    for s in $@ ; do
        [ -x ${vyatta_sbindir}/${s}.init ] && subinit[${#subinit}]=$s
    done
else
    for s in ${all_subinits[@]} ; do
        [ -x ${vyatta_sbindir}/${s}.init ] && subinit[${#subinit}]=$s
    done
fi

GROUP=vyattacfg

boot_stage_start=0

boot_stage_begin()
{
    boot_stage_start=$SECONDS
    log_action_begin_msg "Carrier Router: $1"
}

boot_stage_end()
{
    local status=${1:-0}
    local elapsed=$((SECONDS - boot_stage_start))
    log_action_end_msg "$status" "${elapsed}s"
}

# hostnamectl changes the kernel hostname immediately, while hostsd updates
# /etc/hosts later in the configuration transaction.  Keep sudo and other
# local clients working in that interval.
set_early_hostname()
{
    local new_hostname=$1
    local hosts_file=/etc/hosts
    local hosts_new=/run/carrier-router/hosts.early

    if [[ ! $new_hostname =~ ^[A-Za-z0-9][A-Za-z0-9.-]*$ ]]; then
        log_failure_msg "invalid saved host name: $new_hostname"
        return 1
    fi

    mkdir -p /run/carrier-router
    if [ -r "$hosts_file" ]; then
        awk '$1 != "127.0.1.1" { print }' "$hosts_file" > "$hosts_new"
    else
        printf '127.0.0.1 localhost\n' > "$hosts_new"
    fi
    printf '127.0.1.1 %s\n' "$new_hostname" >> "$hosts_new"
    chmod 644 "$hosts_new"
    chown root:root "$hosts_new"
    mv -f "$hosts_new" "$hosts_file"
    hostnamectl set-hostname --static "$new_hostname"
}

# easy way to make empty file without any command
empty()
{
    >$1
}

# check if bootup of this portion is disabled
disabled () {
    grep -q -w no-vyos-$1 /proc/cmdline
}

motd_helper() {
    MOTD_DIR="/run/motd.d"
    MOTD_FILE="${MOTD_DIR}/99-vyos-update-failed"

    if [[ ! -d ${MOTD_DIR} ]]; then
        mkdir -p ${MOTD_DIR}
    fi

    echo "" > ${MOTD_FILE}
    echo "WARNING: Image update to \"$1\" failed." >> ${MOTD_FILE}
    echo "Please check the logs:" >> ${MOTD_FILE}
    echo "/usr/lib/live/mount/persistence/boot/$1/rw/var/log" >> ${MOTD_FILE}
    echo "Message is cleared on next reboot!" >> ${MOTD_FILE}
    echo "" >> ${MOTD_FILE}
}

# Load encrypted config volume
mount_encrypted_config() {
    persist_path=$(/opt/vyatta/sbin/vyos-persistpath)
    if [ $? == 0 ]; then
        if [ -e $persist_path/boot ]; then
            image_name=$(cat /proc/cmdline | sed -e s+^.*vyos-union=/boot/++ | sed -e 's/ .*$//')
            if [ -z "$image_name" ]; then
                return 0
            fi

            if [ ! -f $persist_path/luks/$image_name ]; then
                return 0
            fi

            if [ ! -e /sys/class/tpm/tpm0 ]; then
                echo "WARN: TPM device not found, encrypted config volume will not be automatically mounted"
                echo "Use 'encryption load' to load volume manually with a key"
                echo "or 'encryption disable' to decrypt volume with a key"
                return 1
            fi

            vyos_tpm_key=$(python3 -c 'from vyos.tpm import read_tpm_key; print(read_tpm_key().decode())' 2>/dev/null)
            if [ $? -ne 0 ]; then
                echo "ERROR: Failed to fetch encryption key from TPM. Encrypted config volume has not been mounted"
                echo "Use 'encryption load' to load volume with recovery key"
                echo "or 'encryption disable' to decrypt volume with recovery key"
                return 1
            fi

            echo $vyos_tpm_key | tr -d '\r\n' | cryptsetup open $persist_path/luks/$image_name vyos_config --key-file=-
            if [ $? -ne 0 ]; then
                echo "ERROR: Failed to decrypt config volume. Encrypted config volume has not been mounted"
                echo "Use 'encryption load' to load volume with recovery key"
                echo "or 'encryption disable' to decrypt volume with recovery key"
                return 1
            fi

            mount /dev/mapper/vyos_config $vyatta_sysconfdir/config

            echo "Mounted encrypted config volume"
        fi
    fi
    return 0
}

unmount_encrypted_config() {
    persist_path=$(/opt/vyatta/sbin/vyos-persistpath)
    if [ $? == 0 ]; then
        if [ -e $persist_path/boot ]; then
            image_name=$(cat /proc/cmdline | sed -e s+^.*vyos-union=/boot/++ | sed -e 's/ .*$//')

            if [ -z "$image_name" ]; then
                return
            fi

            if [ ! -f $persist_path/luks/$image_name ]; then
                return
            fi

            umount $vyatta_sysconfdir/config

            cryptsetup close vyos_config
        fi
    fi
}

# if necessary, provide initial config
init_bootfile () {
    # define and version default boot config if not present
    if [ ! -r $DEFAULT_BOOTFILE ]; then
        if [ -f $vyos_data_dir/config.boot.default ]; then
            cp $vyos_data_dir/config.boot.default $DEFAULT_BOOTFILE
            $vyos_libexec_dir/add-system-version.py >> $DEFAULT_BOOTFILE
        fi
    fi
    mkdir -p "$(dirname $BOOTFILE)"
    if [ ! -L $vyatta_sysconfdir/config/config-db/current ]; then
        if [ -r $LEGACY_BOOTFILE ]; then
            $vyos_op_scripts_dir/config_store_status.py import-projection $LEGACY_BOOTFILE || return 1
        elif [ -r $DEFAULT_BOOTFILE ]; then
            $vyos_op_scripts_dir/config_store_status.py import-projection $DEFAULT_BOOTFILE || return 1
        else
            return 1
        fi
    fi
    $vyos_op_scripts_dir/config_store_status.py sanitize-secrets || return 1
    $vyos_op_scripts_dir/config_store_status.py commands-source > $BOOTFILE || return 1
    chgrp ${GROUP} $BOOTFILE
    chmod 660 $BOOTFILE
    if [ -d $VYCONF_CONFIG_DIR ] ; then
        cp -f $BOOTFILE $VYCONF_CONFIG_DIR/config.boot
        cp -f $DEFAULT_BOOTFILE $VYCONF_CONFIG_DIR/config.failsafe
    fi
}

# Publish changes made by migration or hardware activation back into the
# authoritative store before a later reader regenerates the boot projection.
persist_bootfile_projection ()
{
    $vyos_op_scripts_dir/config_store_status.py import-projection $BOOTFILE || return 1
    $vyos_op_scripts_dir/config_store_status.py commands-source > ${BOOTFILE}.new || return 1
    chgrp ${GROUP} ${BOOTFILE}.new || return 1
    chmod 660 ${BOOTFILE}.new || return 1
    mv -f ${BOOTFILE}.new $BOOTFILE || return 1
    if [ -d $VYCONF_CONFIG_DIR ] ; then
        cp -f $BOOTFILE $VYCONF_CONFIG_DIR/config.boot || return 1
    fi
    return 0
}

# if necessary, migrate initial config
migrate_bootfile ()
{
    if [ -x $vyos_libexec_dir/run-config-migration.py ]; then
        log_progress_msg migrate
        sg ${GROUP} -c "$vyos_libexec_dir/run-config-migration.py $BOOTFILE"
        STATUS=$?
        if [[ "$STATUS" != "0" ]]; then
            return 1
        fi
        persist_bootfile_projection || return 1
    fi
    return 0
}

# configure system-specific settings
system_activate ()
{
    if [ -x $vyos_libexec_dir/run-config-activation.py ]; then
        log_progress_msg activate
        sg ${GROUP} -c "$vyos_libexec_dir/run-config-activation.py $BOOTFILE"
        STATUS=$?
        if [[ "$STATUS" != "0" ]]; then
            return 1
        fi
        persist_bootfile_projection || return 1
    fi
    return 0
}

boot_preparation_failed ()
{
    # Only stage identifiers, never configuration values or credentials.
    printf '%s\n' "$1" >> /run/vyos/boot-preparation-failures
}

# load the initial config
load_bootfile ()
{
    log_progress_msg configure
    (
        if [ -f /etc/default/vyatta-load-boot ]; then
            # build-specific environment for boot-time config loading
            source /etc/default/vyatta-load-boot || return 1
        fi
        if [ ! -x "$vyos_libexec_dir/vyos-boot-config-loader.py" ]; then
            log_failure_msg "boot configuration loader is missing or not executable"
            return 1
        fi
        sg "${GROUP}" -c "\"$vyos_libexec_dir/vyos-boot-config-loader.py\" \"$BOOTFILE\""
    )
    # Preserve the subshell status: otherwise a failed commit is reported READY
    # and the first-boot upgrade recovery condition never sees the failure.
    return $?
}

rollback_failed_upgrade ()
{
    local previous_image running_image persistence_root previous_config images default_image
    previous_image=$(jq -er '.previous_image' "$FIRST_BOOT_FILE") || return 1
    if [[ ! $previous_image =~ ^[A-Za-z0-9][A-Za-z0-9_.+-]*$ ]]; then
        log_failure_msg "invalid previous image in first-boot marker"
        return 1
    fi
    persistence_root=$("${vyatta_sbindir}/vyos-persistpath") || return 1
    # The installer copies config into rw/opt/vyatta/etc/config. /config is a
    # runtime bind mount, not the previous image's on-disk configuration path.
    previous_config="${persistence_root}/boot/${previous_image}/rw${vyatta_sysconfdir}/config"
    if [ ! -d "$previous_config" ]; then
        log_failure_msg "previous image configuration directory is missing"
        return 1
    fi
    images=$("${vyos_op_scripts_dir}/image_info.py" show_images_summary --raw) || return 1
    running_image=$(jq -er '.image_running' <<< "$images") || return 1
    default_image=$(jq -er '.image_default' <<< "$images") || return 1
    if [[ "$previous_image" == "$running_image" ]]; then
        log_failure_msg "previous image is the failing image; automatic reboot cancelled"
        return 1
    fi

    # Never schedule a reboot back into the failing image if selecting the
    # fallback failed. Leave the console available for manual recovery.
    if [[ "$default_image" != "$previous_image" ]] && \
        ! "${vyos_op_scripts_dir}/image_manager.py" --action set --image-name "$previous_image"; then
        log_failure_msg "could not select previous image; automatic reboot cancelled"
        return 1
    fi
    default_image=$("${vyos_op_scripts_dir}/image_info.py" show_images_summary --raw | jq -er '.image_default') || return 1
    if [[ "$default_image" != "$previous_image" ]]; then
        log_failure_msg "previous image selection could not be verified; automatic reboot cancelled"
        return 1
    fi
    jq -n --arg image "$running_image" '{failed_image_update: $image}' \
        > "$previous_config/update_failed" || log_failure_msg "could not record upgrade failure in previous image"
    motd_helper "$running_image"
    log_daemon_msg "Booting failed, reverting to previous image"
    log_progress_msg "$previous_image"
    log_end_msg 0
    log_daemon_msg "Automatic reboot in ${AUTOMATIC_REBOOT_TMO} minutes"
    sync
    if ! shutdown --reboot --no-wall "$AUTOMATIC_REBOOT_TMO"; then
        log_failure_msg "could not schedule automatic reboot"
        return 1
    fi
    log_progress_msg 'Use "reboot cancel" to cancel'
    log_end_msg 0
}

# restore if missing pre-config script
restore_if_missing_preconfig_script ()
{
    if [ ! -x ${vyatta_sysconfdir}/config/scripts/vyos-preconfig-bootup.script ]; then
        mkdir -p ${vyatta_sysconfdir}/config/scripts
        chgrp ${GROUP} ${vyatta_sysconfdir}/config/scripts
        chmod 775 ${vyatta_sysconfdir}/config/scripts
        cp ${vyos_rootfs_dir}/opt/vyatta/etc/config/scripts/vyos-preconfig-bootup.script ${vyatta_sysconfdir}/config/scripts/
        chgrp ${GROUP} ${vyatta_sysconfdir}/config/scripts/vyos-preconfig-bootup.script
        chmod 750 ${vyatta_sysconfdir}/config/scripts/vyos-preconfig-bootup.script
    fi
}

# execute the pre-config script
run_preconfig_script ()
{
    if [ -x $vyatta_sysconfdir/config/scripts/vyos-preconfig-bootup.script ]; then
        $vyatta_sysconfdir/config/scripts/vyos-preconfig-bootup.script
    fi
}

# restore if missing post-config script
restore_if_missing_postconfig_script ()
{
    if [ ! -x ${vyatta_sysconfdir}/config/scripts/vyos-postconfig-bootup.script ]; then
        mkdir -p ${vyatta_sysconfdir}/config/scripts
        chgrp ${GROUP} ${vyatta_sysconfdir}/config/scripts
        chmod 775 ${vyatta_sysconfdir}/config/scripts
        cp ${vyos_rootfs_dir}/opt/vyatta/etc/config/scripts/vyos-postconfig-bootup.script ${vyatta_sysconfdir}/config/scripts/
        chgrp ${GROUP} ${vyatta_sysconfdir}/config/scripts/vyos-postconfig-bootup.script
        chmod 750 ${vyatta_sysconfdir}/config/scripts/vyos-postconfig-bootup.script
    fi
}

# execute the post-config scripts
run_postconfig_scripts ()
{
    if [ -x $vyatta_sysconfdir/config/scripts/vyatta-postconfig-bootup.script ]; then
        $vyatta_sysconfdir/config/scripts/vyatta-postconfig-bootup.script
    fi
    if [ -x $vyatta_sysconfdir/config/scripts/vyos-postconfig-bootup.script ]; then
        $vyatta_sysconfdir/config/scripts/vyos-postconfig-bootup.script
    fi
}

run_postupgrade_script ()
{
    if [ -f $vyatta_sysconfdir/config/.upgraded ]; then
        # Run the system script
        /usr/libexec/vyos/system/post-upgrade

        # Run user scripts
        if [ -d $vyatta_sysconfdir/config/scripts/post-upgrade.d ]; then
            run-parts $vyatta_sysconfdir/config/scripts/post-upgrade.d
        fi
        rm -f $vyatta_sysconfdir/config/.upgraded
    fi
}

#
# On image booted machines, we need to mount /boot from the image-specific
# boot directory so that kernel package installation will put the
# files in the right place.  We also have to mount /boot/grub from the
# system-wide grub directory so that tools that edit the grub.cfg
# file will find it in the expected location.
#
bind_mount_boot ()
{
    persist_path=$(/opt/vyatta/sbin/vyos-persistpath)
    if [ $? == 0 ]; then
        if [ -e $persist_path/boot ]; then
            image_name=$(cat /proc/cmdline | sed -e s+^.*vyos-union=/boot/++ | sed -e 's/ .*$//')

            if [ -n "$image_name" ]; then
                mount --bind $persist_path/boot/$image_name /boot
                if [ $? -ne 0 ]; then
                    echo "Couldn't bind mount /boot"
                fi

                if [ ! -d /boot/grub ]; then
                    mkdir /boot/grub
                fi

                mount --bind $persist_path/boot/grub /boot/grub
                if [ $? -ne 0 ]; then
                    echo "Couldn't bind mount /boot/grub"
                fi
            fi
        fi
    fi
}

# this is called before migration and bind_mount_slash_config to check for
# upgrade data installed by legacy image update tools
copy_legacy_config_path ()
{
    if [ -d /config ] ; then
        if [ -f /config/.upgraded ] ; then
            rm -f /config/.upgraded
            cp -a /config /opt/vyatta/etc
            chgrp -R vyattacfg /opt/vyatta/etc/config
            chmod -R 775 /opt/vyatta/etc/config
            [ ! -f /opt/vyatta/etc/config/config.boot ] || chmod 660 /opt/vyatta/etc/config/config.boot
            touch /opt/vyatta/etc/config/.vyatta_config
            rm -rf /config
        fi
    fi
}

bind_mount_slash_config ()
{
    if [ -d /opt/vyatta/etc/config ]
    then
        if [ ! -d /config ] ; then
            mkdir /config
        fi
        mount --bind /opt/vyatta/etc/config /config
    fi
}

clear_or_override_config_files ()
{
    for conf in snmp/snmpd.conf snmp/snmptrapd.conf snmp/snmp.conf \
        keepalived/keepalived.conf cron.d/vyos-crontab \
        ipvsadm.rules default/ipvsadm resolv.conf
    do
        if [ -s /etc/$conf ] ; then
            empty /etc/$conf
            chmod 0644 /etc/$conf
        fi
    done
}

update_interface_config ()
{
    if [ -d /run/udev/vyos ]; then
        $vyos_libexec_dir/vyos-interface-rescan.py $BOOTFILE
    fi
}

cleanup_post_commit_hooks () {
    # Remove links from the post-commit hooks directory.
    # note that this approach only supports hooks that are "configured",
    # i.e., it does not support hooks that need to always be present.
    cpostdir=$(cli-shell-api getPostCommitHookDir)
    # exclude commit hooks that need to always be present
    excluded="00vyos-sync 10vyatta-log-commit.pl 95-carrier-boot-recovery 99-carrier-auto-save 99vyos-user-postcommit-hooks"
    if [ -d "$cpostdir" ]; then
	    for f in $cpostdir/*; do
	        if [[ ! $excluded =~ $(basename $f) ]]; then
		        rm -f $cpostdir/$(basename $f)
	        fi
	    done
    fi
}

# These are all the default security setting which are later
# overridden when configuration is read. These are the values the
# system defaults.
security_reset ()
{

    # restore NSS cofniguration back to sane system defaults
    # will be overwritten later when configuration is loaded
    cat <<EOF >/etc/nsswitch.conf
passwd:         files
group:          files
shadow:         files
gshadow:        files

# Per T2678, commenting out myhostname
hosts:          files dns #myhostname
networks:       files

protocols:      db files
services:       db files
ethers:         db files
rpc:            db files

netgroup:       nis
EOF

    # restore PAM back to virgin state (no radius/tacacs services)
    pam-auth-update --disable radius-mandatory radius-optional
    rm -f /etc/pam_radius_auth.conf
    pam-auth-update --disable tacplus-mandatory tacplus-optional
    rm -f /etc/tacplus_nss.conf /etc/tacplus_servers
    # and no Google authenticator for 2FA/MFA
    pam-auth-update --disable mfa-google-authenticator

    # Certain configuration files are re-generated by the configuration
    # subsystem and must reside under /etc and cannot easily be moved to /run.
    # So on every boot we simply delete any remaining files and let the CLI
    # regenearte them.

    # PPPoE
    rm -f /etc/ppp/peers/pppoe* /etc/ppp/peers/wlm*

    # IPSec
    rm -rf /etc/ipsec.conf /etc/ipsec.secrets
    find /etc/swanctl -type f | xargs rm -f

    # limit cleanup
    rm -f /etc/security/limits.d/10-vyos.conf

    # iproute2 cleanup
    rm -f /etc/iproute2/rt_tables.d/vyos-*.conf

    # Container
    rm -f /etc/containers/storage.conf /etc/containers/registries.conf /etc/containers/containers.conf
    # Clean all networks and re-create them from our CLI
    rm -f /etc/containers/networks/*

    # System Options (SSH/cURL)
    rm -f /etc/ssh/ssh_config.d/*vyos*.conf
    rm -f /etc/curlrc
}

# XXX: T3885 - generate persistend DHCPv6 DUID (Type4 - UUID based)
gen_duid ()
{
    DUID_FILE="/var/lib/dhcpv6/dhcp6c_duid"
    UUID_FILE="/sys/class/dmi/id/product_uuid"
    UUID_FILE_ALT="/sys/class/dmi/id/product_serial"
    if [ ! -f ${UUID_FILE} ] && [ ! -f ${UUID_FILE_ALT} ]; then
        return 1
    fi

    # DUID is based on the BIOS/EFI UUID. We omit additional - characters
    if [ -f ${UUID_FILE} ]; then
        UUID=$(cat ${UUID_FILE} | tr -d -)
    fi
    if [ -z ${UUID} ]; then
        file_alt="$(cat ${UUID_FILE_ALT})"
        if [ -n "${file_alt}" ]; then
          UUID=$(uuidgen --sha1 --namespace @dns --name ${file_alt} | tr -d -)
        fi
    fi
    # Add DUID type4 (UUID) information
    DUID_TYPE="0004"

    # The length-information (as per RFC6355 UUID is 128 bits long) is in big-endian
    # format - beware when porting to ARM64. The length field consists out of the
    # UUID (128 bit + 16 bits DUID type) resulting in hex 12.
    DUID_LEN="0012"
    if [ "$(echo -n I | od -to2 | head -n1 | cut -f2 -d" " | cut -c6 )" -eq 1 ]; then
        # true on little-endian (x86) systems
        DUID_LEN="1200"
    fi

    for i in $(echo -n ${DUID_LEN}${DUID_TYPE}${UUID} | sed 's/../& /g'); do
        echo -ne "\x$i"
    done > ${DUID_FILE}
}

start ()
{
    local overall_status=0
    local boot_started=$SECONDS
    log_success_msg "Starting Carrier Router"
    mkdir -p /run/vyos
    install -m 0644 /dev/null /run/vyos/boot-preparation-failures

    # reset and clean config files
    security_reset || log_failure_msg "security reset failed"

    # some legacy directories migrated over from old rl-system.init
    mkdir -p /var/run/vyatta /var/log/vyatta
    chgrp vyattacfg /var/run/vyatta /var/log/vyatta
    chmod 775 /var/run/vyatta /var/log/vyatta

    boot_stage_begin "discovering network interfaces"
    # On boot time udev might take a long time to reorder nic's, this will ensure that
    # all udev activity is completed and all nics presented at boot-time will have their
    # final name before continuing with vyos-router initialization.
    # A global udev queue may contain unrelated slow devices.  Ten or more
    # seconds of silence here looked like a failed boot and unnecessarily
    # delayed dataplane activation.  Three seconds is sufficient for initial
    # NIC naming; the later hardware activation still reconciles interfaces
    # by persistent hardware ID.
    udevadm settle --timeout=3
    STATUS=$?
    if [ "$STATUS" -ne 0 ]; then
        log_progress_msg "udev still busy; continuing with hardware-ID reconciliation"
        STATUS=0
    fi
    boot_stage_end "$STATUS"

    # mountpoint for bpf maps required by xdp
    mount -t bpf none /sys/fs/bpf

    # Clear out Debian APT source config file
    empty /etc/apt/sources.list

    # Generate DHCPv6 DUID
    gen_duid || log_failure_msg "could not generate DUID"

    # Mount a temporary filesystem for container networks.
    # Configuration should be loaded from VyOS cli.
    cni_dir="/etc/cni/net.d"
    [ ! -d ${cni_dir} ] && mkdir -p ${cni_dir}
    mount -t tmpfs none ${cni_dir}

    # Init firewall
    nfct helper add rpc inet tcp
    nfct helper add rpc inet udp
    nfct helper add tns inet tcp
    nfct helper add rpc inet6 tcp
    nfct helper add rpc inet6 udp
    nfct helper add tns inet6 tcp
    nft --file /usr/share/vyos/vyos-firewall-init.conf || log_failure_msg "could not initiate firewall rules"

    # Create needed kea directories
    mkdir -p /var/run/kea /run/lock/kea
    chmod 750 /var/run/kea /run/lock/kea
    chown _kea:_kea /var/run/kea /run/lock/kea
    if [ -d /opt/vyatta/etc/config ]; then
        if [ ! -d /opt/vyatta/etc/config/dhcp ]; then
            mkdir /opt/vyatta/etc/config/dhcp
            chmod 750 /opt/vyatta/etc/config/dhcp
            chown _kea:vyattacfg /opt/vyatta/etc/config/dhcp
        fi
    fi

    # Ensure rsyslog is the default syslog daemon
    SYSTEMD_SYSLOG="/etc/systemd/system/syslog.service"
    SYSTEMD_RSYSLOG="/lib/systemd/system/rsyslog.service"
    if [ ! -L ${SYSTEMD_SYSLOG} ] || [ "$(readlink -f ${SYSTEMD_SYSLOG})" != "${SYSTEMD_RSYSLOG}" ]; then
        ln -sf ${SYSTEMD_RSYSLOG} ${SYSTEMD_SYSLOG}
        systemctl daemon-reload
    fi

    # As VyOS does not execute commands that are not present in the CLI we call
    # the script by hand to have a single source for the login banner and MOTD
    ${vyos_conf_scripts_dir}/system_syslog.py || log_failure_msg "could not reset syslog"
    ${vyos_conf_scripts_dir}/system_console.py || log_failure_msg "could not reset serial console"
    ${vyos_conf_scripts_dir}/system_login_banner.py || log_failure_msg "could not reset motd and issue files"
    ${vyos_conf_scripts_dir}/system_option.py || log_failure_msg "could not reset system option files"
    ${vyos_conf_scripts_dir}/system_ip.py || log_failure_msg "could not reset system IPv4 options"
    ${vyos_conf_scripts_dir}/system_ipv6.py || log_failure_msg "could not reset system IPv6 options"
    ${vyos_conf_scripts_dir}/system_conntrack.py || log_failure_msg "could not reset conntrack subsystem"
    ${vyos_conf_scripts_dir}/container.py || log_failure_msg "could not reset container subsystem"

    clear_or_override_config_files || log_failure_msg "could not reset config files"

    # enable some debugging before loading the configuration
    if grep -q vyos-debug /proc/cmdline; then
        log_success_msg "Enable runtime debugging options"
        FRR_DEBUG=$(python3 -c "from vyos.defaults import frr_debug_enable; print(frr_debug_enable)")
        touch $FRR_DEBUG
        touch /tmp/vyos.container.debug
        touch /tmp/vyos.ifconfig.debug
        touch /tmp/vyos.container.debug
        touch /tmp/vyos.smoketest.debug
    fi

    # Cleanup PKI CAs
    if [ -d /usr/local/share/ca-certificates/vyos ]; then
        rm -f /usr/local/share/ca-certificates/vyos/*.crt
        update-ca-certificates >/dev/null 2>&1
    fi

    boot_stage_begin "opening configuration store"
    # ensure the vyatta_configdir supports a large number of inodes since
    # the config hierarchy is often inode-bound (instead of size).
    # impose a minimum and then scale up dynamically with the actual size
    # of the system memory.
    local tmem=$(sed -n 's/^MemTotal: \+\([0-9]\+\) kB$/\1/p' /proc/meminfo)
    local tpages
    local tmpfs_opts="nosuid,nodev,mode=775,nr_inodes=0" #automatically allocate inodes
    mount -o $tmpfs_opts -t tmpfs none ${vyatta_configdir} \
      && chgrp ${GROUP} ${vyatta_configdir}
    boot_stage_end $?

    mount_encrypted_config || { overall_status=1; boot_preparation_failed encrypted-configuration; }

    # config-db uses /config as its canonical path. Bind the real persistent
    # image configuration before the first ConfigStore reader or writer runs;
    # otherwise a revision created in the rootfs /config would be hidden by
    # this mount later in boot.
    disabled copy_legacy_config_path || copy_legacy_config_path
    disabled bind_mount_slash_config || bind_mount_slash_config
    disabled bootfile || init_bootfile || { overall_status=1; boot_preparation_failed configuration-store; }

    # T5239: early read of system hostname as this value is read-only once during
    # FRR initialisation
    tmp=$(${vyos_libexec_dir}/read-saved-value.py --path "system host-name")
    set_early_hostname "$tmp" || { overall_status=1; boot_preparation_failed hostname; }

    ${vyos_conf_scripts_dir}/system_frr.py || log_failure_msg "could not reset FRR config"
    # If for any reason FRR was not started by system_frr.py - start it anyways.
    # This is a safety net!
    systemctl start frr.service

    cleanup_post_commit_hooks

    boot_stage_begin "checking configuration migrations"
    disabled migrate || migrate_bootfile || { overall_status=1; boot_preparation_failed migration; }
    boot_stage_end "$overall_status"

    restore_if_missing_preconfig_script

    run_preconfig_script

    run_postupgrade_script

    boot_stage_begin "reconciling interface hardware IDs"
    update_interface_config || { overall_status=1; boot_preparation_failed hardware-reconciliation; }
    boot_stage_end "$overall_status"

    boot_stage_begin "activating system configuration"
    if disabled system_activate; then
        :
    elif system_activate; then
        # Retirement is one-way, but only after the revision has survived
        # migration and the complete boot transaction has applied.
        rm -f $LEGACY_BOOTFILE
    else
        overall_status=1
        boot_preparation_failed activation
    fi
    boot_stage_end "$overall_status"

    for s in ${subinit[@]} ; do
        if ! disabled $s; then
            log_progress_msg $s
            if ! ${vyatta_sbindir}/${s}.init start
            then log_failure_msg
            overall_status=1
            fi
        fi
    done

    bind_mount_boot

    boot_stage_begin "applying saved configuration"
    disabled configure || load_bootfile || overall_status=1
    boot_stage_end "$overall_status"

    FIRST_BOOT_FILE="/config/first_boot"
    UPDATE_FAILED_BOOT_FILE="/config/update_failed"
    AUTOMATIC_REBOOT_TMO=$(${vyos_libexec_dir}/read-saved-value.py --path "system option reboot-on-upgrade-failure")
    # Image upgrade failed - get previous image name, re-set it as default image
    # and perform an automatic reboot. Automatic reboot timeout can be set via CLI
    if [[ -n $AUTOMATIC_REBOOT_TMO ]] && [[ -f ${FIRST_BOOT_FILE} ]] && [[ ${overall_status} -ne 0 ]]; then
        rollback_failed_upgrade || log_failure_msg "automatic upgrade recovery failed; use console to recover"
    fi
    # After image upgrade failure and once booted into the previous working
    # image, inform the user via MOTD about the failure
    if [[ -n $AUTOMATIC_REBOOT_TMO ]] && [[ -f ${UPDATE_FAILED_BOOT_FILE} ]] ; then
        failed_image_update=$(jq -r '.failed_image_update' ${UPDATE_FAILED_BOOT_FILE})
        motd_helper "${failed_image_update}"
    fi
    # Clear marker files used by automatic reboot on image upgrade mechanism
    if [[ -f ${FIRST_BOOT_FILE} ]]; then
        rm -f ${FIRST_BOOT_FILE}
    fi
    if [[ -f ${UPDATE_FAILED_BOOT_FILE} ]] ; then
        rm -f ${UPDATE_FAILED_BOOT_FILE}
    fi

    telinit q
    chmod g-w,o-w /

    restore_if_missing_postconfig_script

    run_postconfig_scripts
    tmp=$(${vyos_libexec_dir}/read-saved-value.py --path "protocols rpki cache")
    if [[ ! -z "$tmp" ]]; then
        vtysh -c "rpki start"
    fi

    # vyos-netlinkd is ordered After=vyos-router.service. Queue it without
    # waiting so systemd starts it after this service reports readiness; a
    # synchronous start here creates an ordering deadlock.
    systemctl start --no-block vyos-netlinkd.service

    local boot_elapsed=$((SECONDS - boot_started))
    if [ "$overall_status" -eq 0 ]; then
        if [[ $(cat /run/vyos/boot-config-status 2>/dev/null) == 2 ]]; then
            log_success_msg "Carrier Router READY (degraded) in ${boot_elapsed}s; management and available services started"
            log_failure_msg "Some routing interface references were skipped. Check 'show system configuration-status'."
        else
            log_success_msg "Carrier Router READY in ${boot_elapsed}s"
        fi
    else
        log_failure_msg "Carrier Router configuration failed after ${boot_elapsed}s"
        log_failure_msg "System Degraded. Check 'show system configuration-status' for failed components."
    fi
    return "$overall_status"
}

stop()
{
    local -i status=0
    log_daemon_msg "Stopping Carrier Router"

    # As vyos-netlinkd consumes a configuration, we need to stop it prior
    # unmounting /config
    systemctl stop vyos-netlinkd.service

    for ((i=${#sub_inits[@]} - 1; i >= 0; i--)) ; do
    s=${subinit[$i]}
    log_progress_msg $s
    ${vyatta_sbindir}/${s}.init stop
    let status\|=$?
    done
    log_end_msg $status
    log_action_begin_msg "Un-mounting VyOS Config"
    umount ${vyatta_configdir}
    log_action_end_msg $?

    systemctl stop vyconfd.service
    systemctl stop frr.service

    unmount_encrypted_config
}

case "$action" in
    start) start ;;
    stop)  stop ;;
    restart|force-reload) stop && start ;;
    *)  log_failure_msg "usage: $progname [ start|stop|restart ] [ subinit ... ]" ;
    false ;;
esac

exit $?

# Local Variables:
# mode: shell-script
# sh-indentation: 4
# End:
