#!/usr/bin/env bash
logger  -p local0.info "`who -m | cut -d\( -f2 |cut -d\) -f1`  ${BASH_SOURCE}; start;successfully execute ${BASH_SOURCE}"

reboot_env()
{
    if [[ -f "/opt/SEK/reboot.flag" ]];then
        rm -rf "/opt/SEK/reboot.flag"
    fi

    ARCH=$(arch)
    if [[ -f "/usr/lib/systemd/system/rc-local.service" && ${ARCH} == "aarch64" ]];then
        #设置rc-local.service超时时间为5秒，此服务默认超时时长为2min5s，设置之后变为2min10s，避免此服务的停止在系统停止时耗时过长
        sed -i "s/^TimeoutSec.*$/TimeoutSec=5/" /usr/lib/systemd/system/rc-local.service
        ret=$?
        logger  -p local0.info "`who -m | cut -d\( -f2 |cut -d\) -f1` ; modify rc-local.service conf;ret=${ret}"
        #将设置的超时时间生效
        systemctl daemon-reload
        ret=$?
        logger  -p local0.info "`who -m | cut -d\( -f2 |cut -d\) -f1` ; daemon-reload;ret=${ret}"
        sleep 1
        #还原配置，系统重启后按照原生配置生效
        sed -i "s/^TimeoutSec.*$/TimeoutSec=0/" /usr/lib/systemd/system/rc-local.service
        ret=$?
        logger  -p local0.info "`who -m | cut -d\( -f2 |cut -d\) -f1` ; restore rc-local.service conf;ret=${ret}"
    fi

    cat /etc/os-release | grep "SLES" >/dev/null 2>&1
    if [[ $? -eq 0 ]];then
        auto_start_file="/etc/init.d/after.local"
    else
        auto_start_file="/etc/rc.d/rc.local"
    fi

    #生成系统启动项脚本
    echo "#!/bin/bash
    logger -p local0.info \"reboot_sek.sh;Successful;Start reboot_sek.sh successful\"
    echo \"reboot  successfully.\" > /opt/SEK/reboot.flag
    sed -i 's/^.*reboot_sek.*$//g' ${auto_start_file}
    logger -p local0.info \"reboot_sek.sh;Successful;reboot_sek.sh execute successful.\"
    " >/opt/SEK/reboot_sek.sh
    chmod 700 /opt/SEK/reboot_sek.sh

    #设置系统启动项
    grep 'reboot_sek.sh' ${auto_start_file} >/dev/null 2>&1
    [ $? -ne 0 ] && echo "bash /opt/SEK/reboot_sek.sh" >> ${auto_start_file}
    chmod +x  ${auto_start_file}

    service sshd stop
    sleep 59
    sync;sync;sync;sync

    #重启操作系统
    echo "Reboot the OS"
    shutdown -r now
}

reboot_env