#!/bin/sh
# sc4start script file
# The complete path is required in this file.
# MQ 04/30/2015
# MQ 10/12/2015 Added permissions for the web files
# MQ 11/03/2015 Added settings required for dhcpd
# MQ 05/24/2016 Added symlink
# MQ 08/15/2016 Added dnp3
# MQ 11/14/2016 Removes extra LogFiles sym link. 
#               Temporarily removed DNP3. 
# MQ 11/22/2016 Added the shadow file copy
# MQ 01/05/2017 Added permissions for .../log and .../firmware
# MQ 05/05/2017 Added /home/admin/conf/xml
# MQ 08/01/2017 Relocated the FTP log file to /home/admin/log/vsftpd
# MQ 10/01/2018 Install the USB auto mount script.
# MQ 01/24/2019 Worked on making the logfiles sim link work better.
# MQ 06/23/2021 Added ModBus. 
# MQ 09/08/2021 Moved vsftpd.conf from bin/new to conf
# MQ 09/10/2021 Make a new Admin Folder.
# MP 07/06/2022 MQ for MP added permission settings to fix user login.
# MQ 08/08/2022 MQ Set the owner of vsftpd to root.

# Sets the TCP connect timeout to about 20 seconds
echo 2 > /proc/sys/net/ipv4/tcp_syn_retries

#Fix permissions on patches.install script and run it
#This will update the versions of some third party packages
chmod 755 /home/admin/bin/new/patches/patches.install
#NOTE: This script may cause the site controller to reboot if patches were installed
/home/admin/bin/new/patches/patches.install

# Load missing config files (script handles not overwriting)
chmod +x /home/admin/bin/loaddefaultconfs.sh
/home/admin/bin/loaddefaultconfs.sh

# Run script to force setting PBT specific snmpd configs
chmod +x /home/admin/bin/pbtsnmpconfig.sh
/home/admin/bin/pbtsnmpconfig.sh

#Load PBT environment variables.  Do this AFTER loaddefaultconfs.sh
#Note that if you run a process (bscom) outside of this script, you should
# run this command in that shell to load the evn variables
source /home/admin/conf/pbtvars.conf

# Create symlinks so the user's browser can get to the log files
ln -s /ltrx_user /home/admin/www/SiteViewer/Logfiles

# Create a symlink so SiteViewer can get to the classic Web interface
ln -s /home/admin/www/classic /home/admin/www/SiteViewer/Classic

# Create a symlink so SiteViewer can get to batterySpecs.csv
ln -sf /home/admin/conf/batterySpecs.csv /home/admin/www/SiteViewer/batterySpecs.csv

# Make a read only admin folder under admin to help prevent accidentally 
# dropping a firmware update in the wrong place.
mkdir /home/admin/admin
chmod 444 /home/admin/admin


# copy the executable files from the shadow copy to the copy we run
cp -f -p /home/admin/bin/new/sc4main /home/admin/bin/sc4main
cp -f -p /home/admin/bin/new/sc4web /home/admin/bin/sc4web
cp -f -p /home/admin/bin/new/cbxagent /home/admin/bin/cbxagent
cp -f -p /home/admin/bin/new/sc4bscom /home/admin/bin/sc4bscom
cp -f -p /home/admin/bin/new/sc4remcom /home/admin/bin/sc4remcom
cp -f -p /home/admin/bin/new/sc4log /home/admin/bin/sc4log
cp -f -p /home/admin/bin/new/sc4stop /home/admin/bin/sc4stop
cp -f -p /home/admin/bin/new/sc4debug /home/admin/bin/sc4debug
cp -f -p /home/admin/bin/new/sc4config /home/admin/bin/sc4config
cp -f -p /home/admin/bin/new/sc4upload /home/admin/bin/sc4upload
cp -f -p /home/admin/bin/new/sc4dnp3 /home/admin/bin/sc4dnp3
cp -f -p /home/admin/bin/new/modbus /home/admin/bin/modbus

# Make the following files executable
chmod +x /home/admin/bin/sc4main
chmod +x /home/admin/bin/sc4web
chmod +x /home/admin/bin/cbxagent
chmod +x /home/admin/bin/sc4bscom
chmod +x /home/admin/bin/sc4remcom
chmod +x /home/admin/bin/sc4log
chmod +x /home/admin/bin/sc4stop
chmod +x /home/admin/bin/sc4debug
chmod +x /home/admin/bin/sc4config
chmod +x /home/admin/bin/sc4upload
chmod +x /home/admin/bin/sc4dnp3
chmod +x /home/admin/bin/modbus
chmod +x /home/admin/bin/webcert.sh
chmod +x /home/admin/bin/mailcert.sh
chmod +x /home/admin/bin/user.sh
chmod +x /home/admin/bin/fake-hwclock.sh

#PERSISTENT /etc CHANGES
#If you need to make changes to /etc that you want to persist
# do so inside the following if statement and increment SC4STARTVER
SC4STARTVER=1
SC4STARTVERFILE=/etc/sc4startver
VERINETC=$(head $SC4STARTVERFILE)

echo "$SC4STARTVERFILE is at version $VERINETC"

if [ "$VERINETC" != "$SC4STARTVER" ]
then
        echo "Making changes to /etc for sc4start version $SC4STARTVER"
        echo "Unmounting /etc from ramdisk"
        
        # Unmount the RAM disk so the user settings are persistant.
        umount /etc

        addgroup webgroup
        addgroup usrgroup
        adduser webuser -G webgroup -D
        adduser pbtuser -G usrgroup -D -s /home/admin/bin/user.sh

        # Update the FTP config file and user list.
        # This is required for the FTP to work when logged in as pbtuser.
        cp -f -p /home/admin/bin/new/user_list /etc/vsftpd/user_list
        cp -f -p /home/admin/bin/new/chroot_list /etc/vsftpd/chroot_list
        chmod 777 /etc
        #chmod 777 /etc/vsftpd

        # Move the ftp config file to where it needs to be. 
        cp -f -p /home/admin/conf/vsftpd.conf /etc/vsftpd/vsftpd.conf
        chmod -R 711 /etc/vsftpd/
        chown -R root:root /etc/vsftpd/			

        # This setting is required to add our shell script to a list in shells.
        # The FTP with the user user ID and password will not work without this.
        cp -f -p /home/admin/bin/shells /etc/shells

        echo "Changing version in $SC4STARTVERFILE to $SC4STARTVER"
        echo $SC4STARTVER > $SC4STARTVERFILE
        
        #Use for debugging to ensure this doesn't run on every reboot
        #echo "Appending date to /home/admin/bin/sc4startcheck"
        #date >> /home/admin/bin/sc4startcheck
        
        echo "Mounting /etc to ramdisk"
        
        # Restart the RAM disk
        /sbin/ltrx_make_etc_ramdisk
else
        echo "$SC4STARTVERFILE is up to date, not unmounting /etc."
fi
#END PERSISTENT /etc CHANGES

# Move the ftp config file to where it needs to be. 
cp -f -p /home/admin/conf/vsftpd.conf /etc/vsftpd/vsftpd.conf
chmod -R 711 /etc/vsftpd/
chown -R root:root /etc/vsftpd/		

# Make a folder for the FTP log file, remove the old log file.
mkdir /home/admin/log/vsftpd
cp -p /var/log/vsftpd.log /home/admin/log/vsftpd/vsftpd.log
rm /var/log/vsftpd.log

# This is required to update the files when logging in as pbtuser.
chown 775 /home/admin/

# These permissions are required for the web server
chown -R webuser:root /home/admin/www
chown webuser:root /home/admin/www/..
chown webuser:root /home/admin/www/.
chmod -R 775 /home/admin/www/

# User access control
chown -R root:root /home/admin/bin
chown root:root /home/admin/bin/..
chown root:root /home/admin/bin/.
chmod -R 777 /home/admin/bin/
chown -R root:root /home/admin/data
chown root:root /home/admin/data/..
chown root:root /home/admin/data/.
chmod -R 770 /home/admin/data

chown root:root /home/admin/dnp3/..
chown root:root /home/admin/dnp3/.
chmod -R 770 /home/admin/dnp3

chown root:root /home/admin/firmware/..
chown root:root /home/admin/firmware/.
chmod -R 770 /home/admin/firmware

chown -R root:root /home/admin/conf
chown root:root /home/admin/conf/..
chown root:root /home/admin/conf/.
chmod -R 770 /home/admin/conf
# Execute permissions for SV to access conf/batterySpecs.csv
chmod +r /home/admin/conf/batterySpecs.csv
chmod 771 /home/admin/conf/.
chmod 770 /home/admin/conf/..
chmod 770 /home/admin/log
chmod 777 /home/admin/firmware

#Fixes for new image from Lantronix which includes shellinabox
chmod 755 /
chown -R root /lib

# Begin user permission fixes for shellinabox, added MP 07/06/2022
#Note: the following chmod commands may be generated with:
# 1. Create a list of all files and their permissions (this is also useful to diff with other versions):  
#		find /lib -exec ls -ld {} \; | tr -s " " | cut -d' ' -f1,3,4,9 > /tmp/libPermissions.txt
# 2. Generate chmod commands: 
#		cat /tmp/libPermissions.txt | grep -v "^l" | cut -d' ' -f1,4 | awk '{chars=substr($1,2); files=substr($2,1); gsub("-","0",chars); gsub("r","4",chars); gsub("w","2",chars); gsub("x","1",chars); printf "chmod "; for(i=1;i<10;i++) { sum+=substr(chars,i,1); if (i%3 == 0) { printf "%d",sum;sum=0; }; } printf " %s", files; print ""; }'

chmod 755 /lib
chmod 755 /lib/libutil-2.13.so
chmod 755 /lib/ld-2.13.so
chmod 755 /lib/libpthread-2.13.so
chmod 755 /lib/libnss_nis-2.13.so
chmod 755 /lib/libnss_nisplus-2.13.so
chmod 755 /lib/libresolv-2.13.so
chmod 755 /lib/libBrokenLocale-2.13.so
chmod 755 /lib/libnss_files-2.13.so
chmod 755 /lib/libuuid.so.1.3.0
chmod 755 /lib/libnss_compat-2.13.so
chmod 755 /lib/librt-2.13.so
chmod 755 /lib/libthread_db-1.0.so
chmod 755 /lib/libmemusage.so
chmod 644 /lib/libgcc_s.so.1
chmod 755 /lib/libdl-2.13.so
chmod 755 /lib/libpcprofile.so
chmod 755 /lib/libnsl-2.13.so
chmod 644 /lib/libgcc_s.so
chmod 755 /lib/libmount.so.1.1.0
chmod 755 /lib/libcrypt-2.13.so
chmod 755 /lib/libblkid.so.1.1.0
chmod 755 /lib/libnss_dns-2.13.so
chmod 755 /lib/libm-2.13.so
chmod 755 /lib/libnss_hesiod-2.13.so
chmod 755 /lib/libSegFault.so
chmod 755 /lib/firmware
chmod 755 /lib/libanl-2.13.so
chmod 755 /lib/modules
chmod 755 /lib/modules/2.6.39-ts-armv5l
chmod 644 /lib/modules/2.6.39-ts-armv5l/modules.builtin.bin
chmod 644 /lib/modules/2.6.39-ts-armv5l/modules.symbols.bin
chmod 755 /lib/modules/2.6.39-ts-armv5l/kernel
chmod 755 /lib/modules/2.6.39-ts-armv5l/kernel/net
chmod 755 /lib/modules/2.6.39-ts-armv5l/kernel/net/ipv4
chmod 755 /lib/modules/2.6.39-ts-armv5l/kernel/net/ipv4/netfilter
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/ipv4/netfilter/iptable_filter.ko
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/ipv4/netfilter/ipt_REJECT.ko
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/ipv4/netfilter/ip_tables.ko
chmod 755 /lib/modules/2.6.39-ts-armv5l/kernel/net/ipv6
chmod 755 /lib/modules/2.6.39-ts-armv5l/kernel/net/ipv6/netfilter
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/ipv6/netfilter/ip6t_REJECT.ko
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/ipv6/netfilter/ip6table_filter.ko
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/ipv6/netfilter/ip6_tables.ko
chmod 755 /lib/modules/2.6.39-ts-armv5l/kernel/net/netfilter
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/netfilter/x_tables.ko
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/netfilter/xt_mark.ko
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/netfilter/xt_policy.ko
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/netfilter/nfnetlink.ko
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/netfilter/xt_tcpudp.ko
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/netfilter/nfnetlink_log.ko
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/netfilter/xt_NFLOG.ko
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/net/netfilter/xt_TCPMSS.ko
chmod 755 /lib/modules/2.6.39-ts-armv5l/kernel/drivers
chmod 755 /lib/modules/2.6.39-ts-armv5l/kernel/drivers/mmc
chmod 755 /lib/modules/2.6.39-ts-armv5l/kernel/drivers/mmc/host
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/drivers/mmc/host/at91_mci.ko
chmod 755 /lib/modules/2.6.39-ts-armv5l/kernel/drivers/net
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/drivers/net/macb.ko
chmod 755 /lib/modules/2.6.39-ts-armv5l/kernel/drivers/scsi
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/drivers/scsi/scsi_wait_scan.ko
chmod 755 /lib/modules/2.6.39-ts-armv5l/kernel/drivers/hwmon
chmod 644 /lib/modules/2.6.39-ts-armv5l/kernel/drivers/hwmon/jc42.ko
chmod 644 /lib/modules/2.6.39-ts-armv5l/modules.builtin
chmod 644 /lib/modules/2.6.39-ts-armv5l/modules.dep
chmod 644 /lib/modules/2.6.39-ts-armv5l/modules.symbols
chmod 644 /lib/modules/2.6.39-ts-armv5l/modules.dep.bin
chmod 644 /lib/modules/2.6.39-ts-armv5l/modules.devname
chmod 644 /lib/modules/2.6.39-ts-armv5l/modules.softdep
chmod 644 /lib/modules/2.6.39-ts-armv5l/modules.alias
chmod 644 /lib/modules/2.6.39-ts-armv5l/modules.order
chmod 644 /lib/modules/2.6.39-ts-armv5l/modules.alias.bin
chmod 755 /lib/libc-2.13.so

#END shellinabox permissions fixes


# Required for Web page access
# For reasons that I do not understand this code must be here
chown webuser:root /
chown webuser:root /home
chown webuser:root /home/admin
chown webuser:root /home/admin/..
chown webuser:root /home/admin/.

# These settings are required for dhcpd
chmod 755 /home
mkdir /var/db
touch /var/db/dhcpd.leases

# Make the log folders for the Apache server and Net-SNMP 
mkdir /home/admin/log
chmod 776 /home/admin/log
mkdir /home/admin/log/httpd
chmod 644 /home/admin/log/httpd
mkdir /home/admin/log/snmpd
chmod 644 /home/admin/log/snmpd
echo ' '>/home/admin/log/snmpd/snmpd.log
# Remove the default Apache log files, if they exist
rm /var/log/httpd/access_log
rm /var/log/httpd/error_log

# Start with a fresh set of flash drives
rm /ltrx_user/sda1
rm /ltrx_user/sdb1
rm /ltrx_user/sdc1
rm /ltrx_user/sdd1

# Copy the shells file from bin to /etc/shells.  
# To make FTP work with a user password, any shell specified
# for the user must be listed in shells.  Our shells includes "/home/admin/bin/user.sh".
cp -f -p /home/admin/bin/shells /etc/shells

# Copy the snmp config file to the default location /etc/snmp
# We do this so if snmpd is restarted it will get the correct config file.
cp -p /home/admin/conf/snmpd.conf /etc/snmp/snmpd.conf

# Install the revised USB auto Mount script.
cp -f -p /home/admin/bin/auto_usb_mount /sbin/auto_usb_mount 
chmod 755 /sbin/auto_usb_mount

# Set up the httpd.conf file.
HTTPDCONF="/home/admin/conf/httpd.conf"
HTTPDCONFORIG="/home/admin/conf/httpd_orig.conf"
HTTPDCONFSECURE="/home/admin/conf/httpd_secure.conf"

if [[ -L $HTTPDCONF ]]
then
        # httpd.conf has already been set up as a symlink, do nothing.
        echo "httpd.conf symlink exists, no changes needed."
elif [[ -f $HTTPDCONF ]]
then
        echo "changing httpd.conf file to a symlink using the original config."
        # httpd.conf is a file.  This should be updated to a symlink.
        # This is likely an upgrade condition, so maintain the old conf file.
        ln -sf $HTTPDCONFORIG $HTTPDCONF
else
        # !!! Reenable this when ready for https. For now, continue to link to ORIG
		#echo "httpd.conf does not exist, linking to secure config."
        # httpd.conf does not exist.  This is likely a factory install.
        # Use the newer secure config.
        #ln -sf $HTTPDCONFSECURE $HTTPDCONF

		# !!! https is not fully supported, link to original conf.
        echo "changing httpd.conf file to a symlink using the original config."
        ln -sf $HTTPDCONFORIG $HTTPDCONF
fi

# Start the SC4 tasks
# /usr/bin/ntpd -g -c /home/admin/conf/ntp.conf -l /home/admin/log/ntp.log
httpd -f /home/admin/conf/httpd.conf -E /home/admin/log/httpd/start_errs
echo 'Start shellinabox'
shellinaboxd -t -b -u root
echo ' '

#snmpd -Lo: -C -c/home/admin/conf/snmpd.conf -f/home/admin/log/snmpd/snmpd.log
snmpd -Lo: -Lf/home/admin/log/snmpd/snmpd.log -C -c/home/admin/conf/snmpd.conf 
/home/admin/bin/sc4main
/home/admin/bin/sc4log
/home/admin/bin/sc4web
/home/admin/bin/cbxagent
/home/admin/bin/sc4remcom
/home/admin/bin/sc4bscom
/home/admin/bin/sc4dnp3
/home/admin/bin/modbus

# Allow time for the flash drive to mount.
sleep 10s 

# Create a phantom folder so a user logged in as pbtuser can get to the log files
# on the Flash Drive when the drive is mounted at sda1
# 1/24/2019 experiment 1.29.1, enabled rmdir, changed permissions from 777 tp 444 read only. 
#           These changes go with changes made in FindTheFlashDrive() 1.29.1
rmdir /home/admin/logfiles
mkdir /home/admin/logfiles
chmod 444 /home/admin/logfiles
mount --bind /ltrx_user/sda1 /home/admin/logfiles
# chmod -R 444 /home/admin/logfiles

# Creat a mechanism so Frank can get the XML file. Must be read only.
mkdir /home/admin/conf/xml
mount --bind /ltrx_user/pwxcr /home/admin/conf/xml
# mount -o remount,ro /home/admin/conf/xml
echo ' '

# Clean up some unncessary files.
rm /home/admin/bin/setmac.sh

# Update ssh server keys from patches.
chmod 755 /home/admin/bin/new/patches/dropbear_init.install
/home/admin/bin/new/patches/dropbear_init.install

# Set the firewall (if it exists)
FIREWALL_RULES="/home/admin/conf/firewall.rules"
LOG_FILE="/home/admin/conf/firewall.log"

timestamp() {
    date "+%Y-%m-%d %H:%M:%S"
}

echo "" > "$LOG_FILE"

if [ -f "$FIREWALL_RULES" ]; then
    echo "Applying firewall rules from $FIREWALL_RULES"
    echo "$(timestamp) Applying firewall rules from $FIREWALL_RULES" | tee -a "$LOG_FILE"

    if iptables-restore < "$FIREWALL_RULES" >> "$LOG_FILE" 2>&1; then
        echo "$(timestamp) Firewall applied successfully." >> "$LOG_FILE"
        echo "$(timestamp) Current iptables rules:" >> "$LOG_FILE"
        iptables -L -v -n >> "$LOG_FILE" 2>&1
        echo "----------------------------------------" >> "$LOG_FILE"
    else
        echo "$(timestamp) ERROR: Failed to apply firewall rules." >> "$LOG_FILE"
        echo "----------------------------------------" >> "$LOG_FILE"
    fi

    chmod 660 "$FIREWALL_RULES"
    chown pbtuser:root "$FIREWALL_RULES"
else 
    echo "$(timestamp) No firewall configuration available at $FIREWALL_RULES" | tee -a "$LOG_FILE"
fi

chown pbtuser:root "$LOG_FILE"
chmod 660 "$LOG_FILE"

exit 0