# !/bin/bash

WFCRootDir=/opt/wfc
SystemdRootDir=/usr/lib/systemd/system
WFCEtcDir=${WFCRootDir}/etc
FERootDir=${WFCRootDir}/nginx/html/dist
wfcBinDir=${WFCRootDir}/bin
UsrLocalBinDir=/usr/local/bin
wfcDaemon=wfcd
NginxEtcDir=/etc/nginx
NginxConfDir=${NginxEtcDir}/conf.d
CFileList="restconf.yaml crontask.yaml tasks.yaml sshsvc.yaml capconf.yaml wfc.conf"
LogoFileList="zh_brand.png zh_icon.png en_brand.png en_icon.png"

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

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

for CFile in ${CFileList}; do
    if [ ! -e "${WFCEtcDir}/${CFile}" ]; then
        cp -f ${WFCEtcDir}/default/${CFile} ${WFCEtcDir}
    else 
        # mv -f ${WFCEtcDir}/${CFile} ${WFCEtcDir}/${CFile}.bak
        # cp -f ${WFCEtcDir}/default/${CFile} ${WFCEtcDir}
        if [ -e "${WFCBinDir}/upgconf.sh" ]; then
            ${WFCBinDir}/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 "${WFCStaticDir}/logo/${LogoFile}" ]; then
        cp ${WFCStaticDir}/wfc.d/logo/${LogoFile} ${WFCStaticDir}/logo;
    fi                 
done

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

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

systemctl daemon-reload

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

systemctl enable restagent.service
systemctl enable crontask.service
systemctl enable sshsvc.service
systemctl enable captrace.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"
        ${WFCRootDir}/bin/setwfc.sh -m $M_PARAM -c $C_PARAM
    else 
        ${WFCRootDir}/bin/setwfc.sh -m $M_PARAM    
    fi
    # exit while failed to run setwfc.sh
    if [ $? -ne 0 ]; then
        echo "setwfc.sh execution failed. Exiting."
        exit 1
    fi
fi

echo -n "Starting WFC service ... "
systemctl start crontask.service
systemctl start sshsvc.service
systemctl start captrace.service
systemctl start restagent.service
echo "done"
