#!/bin/bash

##################################################################################
# Formats crontab string for periodic APRS beacon and                            #
# replaces the original crontab entry string with this                           #
# new string thus changing the crontab.                                          #
#                                                                                #
# (C)2021 M.T. Konstapel https://meezenest.nl/mees                               #
#                                                                                # 
# This file is part of PE1RXF-APRS-server.                                       #
#                                                                                #
#    PE1RXF-APRS-server is free software: you can redistribute it and/or modify  #
#    it under the terms of the GNU General Public License as published by        #
#    the Free Software Foundation, either version 3 of the License, or           #
#    (at your option) any later version.                                         #
#                                                                                #
#    PE1RXF-APRS-server is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of              #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               #
#    GNU General Public License for more details.                                #
#                                                                                #  
#    You should have received a copy of the GNU General Public License           #
#    along with PE1RXF-APRS-server  If not, see <https://www.gnu.org/licenses/>. #
#                                                                                #
##################################################################################

source /home/marcel/ham/aprs_utils/config.shlib; # load the config library functions

############################################################
# Help                                                     #
############################################################
Help()
{
   # Display Help
   echo "Set interval of APRS beacons in crontab."
   echo
   echo "Syntax: set_beacon.sh [-i <interface>|-t <time>|-c <config-file>]"
   echo "Options:"
   echo "-i     AX.25 interface (ax0 or ax1)"
   echo "-t     Time interval in minutes (0-60), 0 disables beacon"
   echo "-c     Read from config file instead of command line arguments"
   echo
}

############################################################
# This function update the crontab of user marcel          #
############################################################
UpdateCrontab()
{
    # All those escaped characters were a nightmare, but in the end the resulting string was perfect. But executing the string directly from this script proved to be another nightmare:
    # It appears that bash inserts additional escape characters, resulting in the command not working. The solution below is not very elegant, but hey...it works!
    # Let's make a bash script, execute is and remove it again.
    echo "#!/bin/bash" > $sed_tmp_command_file
    echo "$sed_string" >> $sed_tmp_command_file
    chmod u+x $sed_tmp_command_file
    $sed_tmp_command_file
    rm $sed_tmp_command_file
    
    # Update crontab
    /usr/bin/crontab -u marcel $crontab_intermediate_file
}

###############################################################
# Generates beacon files which are send via a crontab process #
###############################################################
ConstructBeaconFile()
{
    if [ "${1}" == "ax0" ]; then
        ConstructBeaconFile_Destination="$(config_get ax0_beacon_destination $ConfigFile)"
        ConstructBeaconFile_Path="$(config_get ax0_beacon_path $ConfigFile)"
        ConstructBeaconFile_Position="$(config_get ax0_beacon_position $ConfigFile)"
        ConstructBeaconFile_Comment="$(config_get ax0_beacon_comment $ConfigFile)"
        ConstructBeaconFile_File="$(config_get ax0_beacon_file $ConfigFile)"
        
        if [ "$ConstructBeaconFile_Path" == "none" ]; then
            ConstructBeaconFile_Beacon="PE1RXF-1>$ConstructBeaconFile_Destination:$ConstructBeaconFile_Position$ConstructBeaconFile_Comment"
        else
            ConstructBeaconFile_Beacon="PE1RXF-1>$ConstructBeaconFile_Destination,$ConstructBeaconFile_Path:$ConstructBeaconFile_Position$ConstructBeaconFile_Comment"
        fi
        
        echo "Beacon for ax0:"
        echo $ConstructBeaconFile_Beacon
        echo $ConstructBeaconFile_Beacon > $ConstructBeaconFile_File

    else
        ConstructBeaconFile_Destination="$(config_get ax1_beacon_destination $ConfigFile)"
        ConstructBeaconFile_Path="$(config_get ax1_beacon_path $ConfigFile)"
        ConstructBeaconFile_Position="$(config_get ax1_beacon_position $ConfigFile)"
        ConstructBeaconFile_Comment="$(config_get ax1_beacon_comment $ConfigFile)"
        ConstructBeaconFile_File="$(config_get ax1_beacon_file $ConfigFile)"
        
        if [ "$ConstructBeaconFile_Path" == "none" ]; then
            ConstructBeaconFile_Beacon="PE1RXF-2>$ConstructBeaconFile_Destination:$ConstructBeaconFile_Position$ConstructBeaconFile_Comment"
        else
            ConstructBeaconFile_Beacon="PE1RXF-2>$ConstructBeaconFile_Destination,$ConstructBeaconFile_Path:$ConstructBeaconFile_Position$ConstructBeaconFile_Comment"
        fi
        
        echo "Beacon for ax1:"
        echo $ConstructBeaconFile_Beacon

        if [ "$ConstructBeaconFile_Path" == "none" ]; then
            ConstructBeaconFile_Beacon="/usr/sbin/beacon -d \"$ConstructBeaconFile_Destination\" -s ax1 '$ConstructBeaconFile_Position$ConstructBeaconFile_Comment'"
        else
            ConstructBeaconFile_Beacon="/usr/sbin/beacon -d \"$ConstructBeaconFile_Destination $ConstructBeaconFile_Path\" -s ax1 '$ConstructBeaconFile_Position$ConstructBeaconFile_Comment'"
        fi
        echo $ConstructBeaconFile_Beacon > $ConstructBeaconFile_File
        
    fi

}
############################################################
############################################################
# Main program                                             #
############################################################
############################################################

# Set variables
Interface="0"
TimeInterval="-1"
crontab_time_string="* * * * *"
crontab_command_string_ax0="/home/marcel/ham/aprs_utils/send_beacon_internal_radio.sh"
crontab_command_string_ax1="/home/marcel/ham/aprs_utils/send_beacon_external_radio.sh"
crontab_full_string="#* * * * * /home/marcel/ham/aprs_utils/send_beacon_internal_radio.sh"
crontab_intermediate_file="/home/marcel/ham/aprs_utils/crontab.pe1rxf"
sed_tmp_command_file="/home/marcel/ham/aprs_utils/sed.cmd"
work_with_config_file="0"

############################################################
# Process the input options.                               #
############################################################
# Get the options
while getopts i:t:c: flag; do
   case "${flag}" in
     i) # interface
         Interface=${OPTARG};;
     t) # time interval beacon
         TimeInterval=${OPTARG};;
     c) # work with config_file
         work_with_config_file="1"
         ConfigFile=${OPTARG};;         
     \?) # Invalid option
         echo "Syntax error!"
         Help
         exit;;         
   esac
done

##############################################################
# Get Beacon Timer Interval and translate to crontab syntax  #
##############################################################

# Read values from config-file
if [ "$work_with_config_file" -eq "1" ]; then
    
    
    for ax_port in ax0 ax1 
    do
        Interface="$ax_port"
        if [ "$Interface" == "ax0" ]; then
            TimeInterval="$(config_get ax0_beacon_time $ConfigFile)"
        else
            TimeInterval="$(config_get ax1_beacon_time $ConfigFile)"
        fi
        
        # Let's generate new beacon files according to values in configuration file
        ConstructBeaconFile $Interface

        # Every 1 to 59 minutes
        if [ "$TimeInterval" -gt 0 ] && [ "$TimeInterval" -lt 60 ]; then
            crontab_time_string="*/$TimeInterval * * * *"
        # Never
        elif [ "$TimeInterval" -eq 0 ]; then
            crontab_time_string="#* * * * *"    
        # Every hour
        elif [ "$TimeInterval" -eq 60 ]; then
            crontab_time_string="0 * * * *"    
        else
            echo "No valid value. Using default."
            crontab_time_string="#* * * * *"            
        fi
        
        # Select ax.25 port
        if [ "$Interface" == "ax0" ]; then
            crontab_full_string="$crontab_time_string $crontab_command_string_ax0"
            sed_string="sed -i \"/send_beacon_internal_radio/c\\$crontab_full_string\" $crontab_intermediate_file"
        elif [ "$Interface" == "ax1" ]; then
            crontab_full_string="$crontab_time_string $crontab_command_string_ax1"
            sed_string="sed -i \"/send_beacon_external_radio/c\\$crontab_full_string\" $crontab_intermediate_file"
        else
            echo "No valid value. Using default."
            crontab_full_string="$crontab_time_string $crontab_command_string_ax0"
            sed_string="sed -i \"/send_beacon_internal_radio/c\\$crontab_full_string\" $crontab_intermediate_file"           
        fi
        
        UpdateCrontab
        
    done
    
    printf -- "Values read from file: %s$ConfigFile\n";
    printf -- "ax0 beacon time: %s\n" "$(config_get ax0_beacon_time $ConfigFile)";
    printf -- "ax1 beacon time: %s\n" "$(config_get ax1_beacon_time $ConfigFile)";
# Read values from command line arguments
else

    # Every 1 to 59 minutes
    if [ "$TimeInterval" -gt 0 ] && [ "$TimeInterval" -lt 60 ]; then
        crontab_time_string="*/$TimeInterval * * * *"
    # Never
    elif [ "$TimeInterval" -eq 0 ]; then
        crontab_time_string="#* * * * *"    
    # Every hour
    elif [ "$TimeInterval" -eq 60 ]; then
        crontab_time_string="0 * * * *"    
    else
        echo "Syntax error!"
        Help
        exit
    fi

    # Select ax.25 port
    if [ "$Interface" == "ax0" ]; then
        crontab_full_string="$crontab_time_string $crontab_command_string_ax0"
        sed_string="sed -i \"/send_beacon_internal_radio/c\\$crontab_full_string\" $crontab_intermediate_file"
    elif [ "$Interface" == "ax1" ]; then
        crontab_full_string="$crontab_time_string $crontab_command_string_ax1"
        sed_string="sed -i \"/send_beacon_external_radio/c\\$crontab_full_string\" $crontab_intermediate_file"
    else
        echo "Syntax error!"
        Help
        exit
    fi
    
    UpdateCrontab
fi


