# !/bin/bash
# Execute the script after installation
RootDir=/usr/local/etc/omc

# Perform post-installation configuration
echo ""
echo "Output: $RootDir"
echo "Service:"
echo "    sudo systemctl [start|stop|status|restart] omc.service"
echo ""

# Check if this is the first installation or upgrade
if [ ! -f $RootDir/machine.ini ]; then
    # First installation, perform the related operations
    chmod +rx /usr/local/bin/omc
    cp $RootDir/default/omc.conf $RootDir/omc.conf
    cp $RootDir/default/omc.yaml $RootDir/omc.yaml
    cp $RootDir/web/default/config.js $RootDir/web/config.js

    # read environment parameter and to do
    if [ -n "$M_PARAM" ] && [ -n "$C_PARAM" ]; then
      bash $RootDir/script/setup.sh -i -m $M_PARAM -c $C_PARAM
    elif [ -n "$C_PARAM" ]; then 
      bash $RootDir/script/setup.sh -i -c $C_PARAM
    else
      bash $RootDir/script/setup.sh -i
    fi
    if [ $? -ne 0 ]; then
      echo "Initialization failure."
      rm -rf $RootDir
      exit 1
    fi

    systemctl daemon-reload
    systemctl enable omc.service
    systemctl daemon-reload
    systemctl restart omc.service
else
    # Operation when upgrading
    if [ ! -f $RootDir/omc.conf ]; then
      chmod +rx /usr/local/bin/omc
      cp $RootDir/default/omc.conf $RootDir/omc.conf
      cp $RootDir/default/omc.yaml $RootDir/omc.yaml
      cp $RootDir/web/default/config.js $RootDir/web/config.js
    fi
    # Override Configuration
    if ! grep -q "# route service configuration" $RootDir/omc.yaml; then
      cp -rf $RootDir/default/omc.yaml $RootDir/omc.yaml
    fi

    bash $RootDir/script/setup.sh -u
    if [ $? -ne 0 ]; then
        echo "Upgrade failed."
        exit 1
    fi

    systemctl daemon-reload
    systemctl restart omc.service
fi
echo ""
