# !/bin/bash

OMCRootDir=/usr/local/omc
SystemdRootDir=/lib/systemd/system
OMCEtcDir=${OMCRootDir}/etc
FERootDir=${OMCRootDir}/htdocs/front
OmcBinDir=${OMCRootDir}/bin
OMCStaticDir=${OMCRootDir}/static
UsrLocalBinDir=/usr/local/bin
OmcDaemon=omcd
NginxEtcDir=/etc/nginx
NginxConfDir=${NginxEtcDir}/conf.d
CFileList="restconf.yaml sshsvc.yaml omc.conf"
LogoFileList="zh_brand.png zh_icon.png en_brand.png en_icon.png"

echo ""
echo "* To start/stop/restart/status omc service, please run:"
echo "    sudo systemctl start/stop/restart/status restagent.service"
echo "    sudo systemctl start/stop/restart/status sshsvc.service"
echo "    or run: "
echo "    sudo /usr/local/omc/bin/omcsvc.sh start/stop/restart/status"
echo ""

cd ${UsrLocalBinDir}
if [ ! -e ${OmcDaemon} ]; then  ln -s ${OmcBinDir}/omcsvc.sh ${OmcDaemon}; fi

chmod +rx ${OMCRootDir}/bin/*
chmod +rx ${OMCRootDir}/*
chmod +rx ${UsrLocalBinDir}/*
chmod -R 755 ${OMCRootDir}/htdocs/front

for CFile in ${CFileList}; do
    if [ ! -e "${OMCEtcDir}/${CFile}" ]; then
        cp -f ${OMCEtcDir}/default/${CFile} ${OMCEtcDir}
    else 
        # mv -f ${OMCEtcDir}/${CFile} ${OMCEtcDir}/${CFile}.bak
        # cp -f ${OMCEtcDir}/default/${CFile} ${OMCEtcDir}
        if [ -e "${OMCBinDir}/upgconf.sh" ]; then
            ${OMCBinDir}/upgconf.sh
        fi
    fi                  
done

if [ ! -e "${FERootDir}/config.js" ]; then    
    cp ${FERootDir}/default/config.js ${FERootDir}; 
fi

for LogoFile in ${LogoFileList}; do
    if [ ! -e "${OMCStaticDir}/logo/${LogoFile}" ]; then
        cp ${OMCStaticDir}/omc.d/logo/${LogoFile} ${OMCStaticDir}/logo;
    fi                 
done

if ! id -u omc >/dev/null 2>&1 ; then     
    useradd -d /opt/omc -m -s /bin/bash -pomc123 omc; 
    mkdir -p /opt/omc/ftp
else 
    echo "user omc exist"; 
fi

if [ ! -e "${NginxConfDir}/omc.conf" ]; then
    mkdir -p ${NginxConfDir}
    cp -f ${OMCEtcDir}/nginx/omc.conf ${NginxConfDir}; 
fi

systemctl daemon-reload

# disable auto upgrade
systemctl disable --now unattended-upgrades

systemctl enable restagent.service
systemctl enable sshsvc.service

systemctl daemon-reload

# read environment parameter and to do 
if [ "$M_PARAM" = "install" -o "$M_PARAM" = "upgrade" ]; then
    echo "M parameter: $M_PARAM"
    if [ -n "$C_PARAM" ]; then
        echo "C parameter: $C_PARAM"
        ${OMCRootDir}/bin/setomc.sh -m $M_PARAM -c $C_PARAM
    else 
        ${OMCRootDir}/bin/setomc.sh -m $M_PARAM    
    fi
    # exit while failed to run setomc.sh
    if [ $? -ne 0 ]; then
        echo "setomc.sh execution failed. Exiting."
        exit 1
    fi
fi

echo -n "Starting OMC service ... "
systemctl start sshsvc.service
systemctl start restagent.service
echo "done"
