#!/bin/bash
CFGFILE="mbconfig.cfg"
#check volume is mounted with expected files
if [ ! -f /home/openplc/volume/$PROG_FILE ]; then
echo "Structured text file missing!"
exit 1
fi
if [ ! -f /home/openplc/volume/mbconfig.cfg ]; then
echo "Config file missing!"
exit 1
fi
#don't know what this can be used for
sed -e s/DEVICE_NAME/$DEVICE_NAME/ -e s/DEVICE_IP/$DEVICE_IP/ -e s/DEVICE_CMD_REG/$DEVICE_CMD_REG/ -e s/DEVICE_STATUS_REG/$DEVICE_STATUS_REG/ /home/openplc/volume/mbconfig.cfg > /home/openplc/volume/tmp && mv /home/openplc/volume/tmp /home/openplc/volume/mbconfig.cfg
echo "DONE" >> /home/openplc/volume/log
## define the program to execute
# add new
SQL_ADD_SCRIPT_PROG="INSERT INTO Programs (Name, Description, File, Date_upload) VALUES ($PROG_NAME,$PROG_DESC,$PROG_FILE, strftime('%s', 'now'));"
cp /home/openplc/volume/ script.st /home/openplc/OpenPLC_v3/webserver/st_files sqlite3 /home/openplc/OpenPLC_v3/webserver/openplc.db "$SQL_ADD_SCRIPT_PROG"
#compile and define active program : this should end up with an executable named openplc in webserver/core
rm /home/openplc/OpenPLC_v3/webserver/core/openplc
cd /home/openplc/OpenPLC_v3/webserver/
if [ ! -f /home/openplc/OpenPLC_v3/webserver/core/openplc ]; then
echo "Executable generated from $PROG_FILE file missing! Compilation must have failed"
exit 1
fi
## define slave device
SQL_ADD_DEVICE="INSERT INTO Slave_dev (dev_name, dev_type, slave_id, ip_address, ip_port, di_start, di_size, coil_start, coil_size, ir_start, ir_size, hr_read_start, hr_read_size, hr_write_start, hr_write_size) VALUES ($DEVICE_NAME,'TCP',0,$DEVICE_IP,'502','0','0','0','0',$DEVICE_STATUS_REG,'1','0','0',$DEVICE_CMD_REG,'1');"
cp /home/openplc/volume/mbconfig.cfg /home/openplc/OpenPLC_v3/webserver
sqlite3 /home/openplc/OpenPLC_v3/webserver/openplc.db "$SQL_ADD_DEVICE"
## start in run mode
SQL_AUTO_START="UPDATE Settings SET Value = 'true' WHERE Key = 'Start_run_mode';"
sqlite3 /home/openplc/OpenPLC_v3/webserver/openplc.db "$SQL_AUTO_START"