#!/bin/bash
SCRIPTVERSION='v1.0'
SCRIPT=$(readlink -f $0)
SCRIPTPATH=`dirname $SCRIPT`
PIA_CONF_FILE=${SCRIPTPATH}'/../config/pialert.conf'
PIA_CONF_FILE_PATH=${SCRIPTPATH}'/../config'
PIA_DB_FILE=${SCRIPTPATH}'/../db/pialert.db'
PIA_DB_FILE_PATH=${SCRIPTPATH}'/../db'
#Textformating
bold=$(tput bold)
normal=$(tput sgr0)

case $1 in

  help)

read -r -d '' PIALERTCLI_MANUAL << EOM
pialert-cli $SCRIPTVERSION (https://github.com/leiweibau/Pi.Alert)
Command line tool of Pi.Alert, which is used to support the front and back end.
Usage: ${bold}pialert-cli <command>${normal}

This is the list of supported commands

 ${bold}disable_scan <MIN>${normal}
    Stops all active scans and prevents new scans from starting. You can set a
    Timeout in minutes. If no timeout is set, Pi.Alert restarts itself with
    the next scan after 10min.

 ${bold}disable_service_mon${normal}
    Allows the start of new scans again. If the SCAN_WEBSERVICES parameter
    does not exist yet, it will be created and set to FALSE.

 ${bold}enable_scan${normal}
    Allows the start of new scans again.

 ${bold}enable_service_mon${normal}"
    Enable Web Service Monitoring. If the SCAN_WEBSERVICES parameter does not
    exist yet, it will be created and set to TRUE.

 ${bold}reporting_test${normal}
    Test reporting for all activated services.

 ${bold}rewrite_config${normal}
    A new decluttered config file (pialert-rewritten.conf) will be created.

 ${bold}set_apikey${normal}
    With the API key it is possible to make queries to the database without
    using the web page. If an API key already exists, it will be replaced.

 ${bold}set_autopassword${normal}
    Sets a new random password as a hashed value and show it plaintext in the
    console. If the PIALERT_WEB_PROTECTION parameter does not exist yet, it 
    will be created and set to TRUE (login enabled).

 ${bold}set_login${normal}
    Sets the parameter PIALERT_WEB_PROTECTION in the config file to TRUE. If 
    the parameter is not present, it will be created. Additionally the default
    password '123456' is set.

 ${bold}set_password <password>${normal}
    Sets the new password as a hashed value. If the PIALERT_WEB_PROTECTION
    parameter does not exist yet, it will be created and set to TRUE (login
    enabled).

 ${bold}set_permissions${normal}
    Repair file permissions

 ${bold}set_sudoers${normal}
    Create sudoer file for www-data and Pi.Alert user

 ${bold}unset_login${normal}
    Sets the parameter PIALERT_WEB_PROTECTION in the config file to FALSE. If
    the parameter is not present, it will be created. Additionally the default
    password '123456' is set.

 ${bold}unset_sudoers${normal}
    Delete sudoer file for www-data and Pi.Alert user

 ${bold}update_db${normal}
    The script tries to make the database compatible for this fork.

2023 leiweibau (https://github.com/leiweibau/Pi.Alert) (https://leiweibau.net)
EOM

    echo -e "$PIALERTCLI_MANUAL" | more
    ;;

  set_login)
    ## Check if PIALERT_WEB_PROTECTION exists
    CHECK_PROT=$(grep "PIALERT_WEB_PROTECTION" $PIA_CONF_FILE | wc -l)
    if [ $CHECK_PROT -eq 0 ]
    then
        ## Create PIALERT_WEB_PROTECTION and enable it
        sed -i "/^VENDORS_DB.*/a PIALERT_WEB_PROTECTION = True" $PIA_CONF_FILE
        sed -i "/^PIALERT_WEB_PROTECTION.*/a PIALERT_WEB_PASSWORD = '8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92'" $PIA_CONF_FILE
    else
        ## Switch PIALERT_WEB_PROTECTION to enable
        sed -i "/PIALERT_WEB_PROTECTION/c\PIALERT_WEB_PROTECTION = True" $PIA_CONF_FILE
    fi
    echo "Login is now enabled"
    ;;

  unset_login)
    ## Check if PIALERT_WEB_PROTECTION exists
    CHECK_PROT=$(grep "PIALERT_WEB_PROTECTION" $PIA_CONF_FILE | wc -l)
    if [ $CHECK_PROT -eq 0 ]
    then
        ## Create PIALERT_WEB_PROTECTION and disable it
        sed -i "/^VENDORS_DB.*/a PIALERT_WEB_PROTECTION = False" $PIA_CONF_FILE
        sed -i "/^PIALERT_WEB_PROTECTION.*/a PIALERT_WEB_PASSWORD = '8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92'" $PIA_CONF_FILE
    else
        ## Switch PIALERT_WEB_PROTECTION to disable
        sed -i "/PIALERT_WEB_PROTECTION/c\PIALERT_WEB_PROTECTION = False" $PIA_CONF_FILE
    fi
    echo "Login is now disabled"
    ;;

  set_password)
    PIA_PASS=$2
    ## Check if PIALERT_WEB_PROTECTION exists
    CHECK_PROT=$(grep "PIALERT_WEB_PROTECTION" $PIA_CONF_FILE | wc -l)
    if [ $CHECK_PROT -eq 0 ]
    then
        ## Create PIALERT_WEB_PROTECTION and enable it
        sed -i "/^VENDORS_DB.*/a PIALERT_WEB_PROTECTION = True" $PIA_CONF_FILE
    fi
    ## Prepare Hash
    PIA_PASS_HASH=$(echo -n $PIA_PASS | sha256sum | awk '{print $1}')
    echo "   The hashed password is:"
    echo "   $PIA_PASS_HASH"
    ## Check if the password parameter is set
    CHECK_PWD=$(grep "PIALERT_WEB_PASSWORD" $PIA_CONF_FILE | wc -l)
    if [ $CHECK_PWD -eq 0 ]
    then
        sed -i "/^PIALERT_WEB_PROTECTION.*/a PIALERT_WEB_PASSWORD = '$PIA_PASS_HASH'" $PIA_CONF_FILE
    else
        sed -i "/PIALERT_WEB_PASSWORD/c\PIALERT_WEB_PASSWORD = '$PIA_PASS_HASH'" $PIA_CONF_FILE
    fi
    echo ""
    echo "The new password is set"
    ;;

  set_autopassword)
    ## Check if PIALERT_WEB_PROTECTION exists
    CHECK_PROT=$(grep "PIALERT_WEB_PROTECTION" $PIA_CONF_FILE | wc -l)
    if [ $CHECK_PROT -eq 0 ]
    then
        ## Create PIALERT_WEB_PROTECTION and enable it
        sed -i "/^VENDORS_DB.*/a PIALERT_WEB_PROTECTION = True" $PIA_CONF_FILE
    fi
    ## Create autopassword
    PIA_AUTOPASS=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)
    echo "   The password is: $PIA_AUTOPASS"
    ## Prepare Hash
    PIA_AUTOPASS_HASH=$(echo -n $PIA_AUTOPASS | sha256sum | awk '{print $1}')
    echo "   The hashed password is:"
    echo "   $PIA_AUTOPASS_HASH"
    ## Check if the password parameter is set
    CHECK_PWD=$(grep "PIALERT_WEB_PASSWORD" $PIA_CONF_FILE | wc -l)
    if [ $CHECK_PWD -eq 0 ]
    then
        ## Create password parameter
        sed -i "/^PIALERT_WEB_PROTECTION.*/a PIALERT_WEB_PASSWORD = '$PIA_AUTOPASS_HASH'" $PIA_CONF_FILE
    else
        ## Overwrite password parameter
        sed -i "/PIALERT_WEB_PASSWORD/c\PIALERT_WEB_PASSWORD = '$PIA_AUTOPASS_HASH'" $PIA_CONF_FILE
    fi
    echo ""
    echo "The new password is set"
    ;;

  disable_scan)
    ## stop active scans
    STOPTIMER=$2
    re='^[0-9]+$'
    if ! [[ $STOPTIMER =~ $re ]] ; then
       echo "No timeout is set. Pi.Alert restarts itself with the next scan after 10min."
       STOPTIMER=10
    fi
    sudo killall arp-scan
    echo $STOPTIMER > ${SCRIPTPATH}/../db/setting_stoparpscan
    /usr/bin/python3 ${SCRIPTPATH}/pialert.py reporting_starttimer
    echo "The arp-scan is disabled"
    ;;

  enable_scan)
    ## stop active scans
    rm ${SCRIPTPATH}/../db/setting_stoparpscan
    /usr/bin/python3 ${SCRIPTPATH}/pialert.py reporting_stoptimer
    echo "The arp-scan is enabled"
    ;;

  enable_service_mon)
    ## Check if SCAN_WEBSERVICES exists
    CHECK_PROT=$(grep "SCAN_WEBSERVICES" $PIA_CONF_FILE | wc -l)
    if [ $CHECK_PROT -eq 0 ]
    then
        ## Create SCAN_WEBSERVICES and enable it
        sed -i "/^VENDORS_DB.*/a SCAN_WEBSERVICES = True" $PIA_CONF_FILE
    else
        ## Switch SCAN_WEBSERVICES to enable
        sed -i "/SCAN_WEBSERVICES/c\SCAN_WEBSERVICES = True" $PIA_CONF_FILE
    fi
    echo "Web Service Monitoring is now enabled"
    ;;

  disable_service_mon)
    ## Check if SCAN_WEBSERVICES exists
    CHECK_PROT=$(grep "SCAN_WEBSERVICES" $PIA_CONF_FILE | wc -l)
    if [ $CHECK_PROT -eq 0 ]
    then
        ## Create SCAN_WEBSERVICES and disable it
        sed -i "/^VENDORS_DB.*/a SCAN_WEBSERVICES = False" $PIA_CONF_FILE
    else
        ## Switch SCAN_WEBSERVICES to disable
        sed -i "/SCAN_WEBSERVICES/c\SCAN_WEBSERVICES = False" $PIA_CONF_FILE
    fi
    echo "Web Service Monitoring is now disabled"
    ;;

  update_db)
    ## update database
    echo "################################################################################"
    echo "# You are planning to update the Pi.Alert DB. Please make sure that no scan    #"
    echo "# takes place during the update to avoid possible database errors afterwards!  #"
    echo "#                                                                              #"
    echo "# This can be done by pausing the Arp scan via the settings page. However,     #"
    echo "# scans that are already running will not be terminated. (STRG+C to Abort)     #"
    echo "################################################################################"
    echo ""
    echo ""
    printf "%s " "Press enter to continue"
    read ans
    echo ""
    echo "Update DB $PIA_DB_FILE"
    echo -e "\nPurge old db backup"
    rm ${PIA_DB_FILE_PATH}/pialert.db.bak
    echo -e "...Create backup before insert new table"
    sqlite3 "$PIA_DB_FILE" ".backup '${PIA_DB_FILE_PATH}/pialert.db.bak'"
    # Online_History
    echo -e "...Insert new table 'Online_History' to DB"
    sqlite3 $PIA_DB_FILE "CREATE TABLE IF NOT EXISTS 'Online_History' ('Index' INTEGER, 'Scan_Date' TEXT, 'Online_Devices' INTEGER, 'Down_Devices' INTEGER, 'All_Devices' INTEGER, 'Archived_Devices' INTEGER, PRIMARY KEY('Index' AUTOINCREMENT));"
    # network_infrastructure
    echo -e "...Insert new table 'network_infrastructure' to DB"
    sqlite3 $PIA_DB_FILE "CREATE TABLE IF NOT EXISTS 'network_infrastructure' ('device_id' INTEGER, 'net_device_name' TEXT NOT NULL, 'net_device_typ' TEXT NOT NULL, 'net_device_port' INTEGER, 'net_downstream_devices' TEXT, PRIMARY KEY('device_id' AUTOINCREMENT));"
    # Devices.dev_Infrastructure
    echo -e "...Insert new column 'dev_Infrastructure' to table 'Devices' to DB"
    existing=$(sqlite3 $PIA_DB_FILE "PRAGMA table_info('Devices');" | awk -F\| '{print $2}' | grep -wci "dev_Infrastructure")
    if [ $existing -eq 0 ]; then
      sqlite3 $PIA_DB_FILE "ALTER TABLE 'Devices' ADD COLUMN 'dev_Infrastructure' INTEGER;"
    else
      echo "        Column 'dev_Infrastructure' already exists in the 'Devices' table."
    fi
    # Devices.dev_Infrastructure_port
    echo -e "...Insert new column 'dev_Infrastructure_port' to table 'Devices' to DB"
    existing=$(sqlite3 $PIA_DB_FILE "PRAGMA table_info('Devices');" | awk -F\| '{print $2}' | grep -wci "dev_Infrastructure_port")
    if [ $existing -eq 0 ]; then
      sqlite3 $PIA_DB_FILE "ALTER TABLE 'Devices' ADD COLUMN 'dev_Infrastructure_port' INTEGER;"
    else
      echo "        Column 'dev_Infrastructure_port' already exists in the 'Devices' table."
    fi
    # network_infrastructure.net_downstream_devices
    echo -e "...Insert new column 'net_downstream_devices' to table 'network_infrastructure' to DB"
    existing=$(sqlite3 $PIA_DB_FILE "PRAGMA table_info('Devices');" | awk -F\| '{print $2}' | grep -wci "dev_Infrastructure_port")
    if [ $existing -eq 0 ]; then
      sqlite3 $PIA_DB_FILE "ALTER TABLE 'network_infrastructure' ADD COLUMN 'net_downstream_devices' TEXT;"
    else
      echo "        Column 'net_downstream_devices' already exists in the 'network_infrastructure' table."
    fi
    # network_dumb_dev
    echo -e "...Insert new table 'network_dumb_dev' to DB"
    sqlite3 $PIA_DB_FILE "CREATE TABLE IF NOT EXISTS 'network_dumb_dev' ('dev_Name' TEXT, 'dev_MAC' TEXT, 'dev_Infrastructure' INTEGER, 'dev_Infrastructure_port' INTEGER, 'dev_PresentLastScan' TEXT, 'dev_LastIP' TEXT, 'id' INTEGER, PRIMARY KEY('id' AUTOINCREMENT));"
    # Services_Events
    echo -e "...Insert new table 'Services_Events' to DB"
    sqlite3 $PIA_DB_FILE "CREATE TABLE IF NOT EXISTS 'Services_Events' ('moneve_URL' TEXT NOT NULL, 'moneve_DateTime' TEXT NOT NULL, 'moneve_StatusCode' NUMERIC NOT NULL, 'moneve_Latency' TEXT NOT NULL, 'moneve_TargetIP' TEXT NOT NULL);"
    # Services_CurrentScan
    echo -e "...Insert new table 'Services_CurrentScan' to DB"
    sqlite3 $PIA_DB_FILE "CREATE TABLE IF NOT EXISTS 'Services_CurrentScan' ('cur_URL' TEXT NOT NULL, 'cur_DateTime' TEXT NOT NULL, 'cur_StatusCode' NUMERIC NOT NULL, 'cur_Latency' TEXT NOT NULL, 'cur_AlertEvents' INTEGER DEFAULT 0, 'cur_AlertDown' INTEGER DEFAULT 0, 'cur_StatusChanged' INTEGER DEFAULT 0, 'cur_LatencyChanged' INTEGER DEFAULT 0, 'cur_TargetIP' TEXT NOT NULL, 'cur_StatusCode_prev' NUMERIC, 'cur_TargetIP_prev' TEXT);"
    # Services
    echo -e "...Insert new table 'Services' to DB"
    sqlite3 $PIA_DB_FILE "CREATE TABLE IF NOT EXISTS 'Services' ('mon_URL' TEXT NOT NULL, 'mon_MAC' TEXT, 'mon_LastStatus' NUMERIC NOT NULL, 'mon_LastLatency' TEXT NOT NULL, 'mon_LastScan' TEXT NOT NULL, 'mon_Tags' TEXT, 'mon_AlertEvents' INTEGER DEFAULT 0, 'mon_AlertDown' INTEGER DEFAULT 0, 'mon_TargetIP' TEXT NOT NULL, PRIMARY KEY('mon_URL'));"
    # Services.mon_Notes
    echo -e "...Insert new column 'mon_Notes' to table 'Services' to DB"
    existing=$(sqlite3 $PIA_DB_FILE "PRAGMA table_info('Services');" | awk -F\| '{print $2}' | grep -wci "mon_Notes")
    if [ $existing -eq 0 ]; then
      sqlite3 $PIA_DB_FILE "ALTER TABLE 'Services' ADD COLUMN 'mon_Notes' TEXT;"
    else
      echo "        Column 'mon_Notes' already exists in the 'Services' table."
    fi

    echo -e "\nUpdate finished!\n"

    ;;

  set_apikey)
    ## Create API-Key
    ##PIA_APIKEY_RAND="Test"
    PIA_APIKEY_RAND=$(head -c 4096 /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 60 | head -n 1)
    ## Check if PIALERT_APIKEY exists
    CHECK_API=$(grep "PIALERT_APIKEY" $PIA_CONF_FILE | wc -l)
    if [ $CHECK_API -eq 0 ]
    then
        ## Create PIALERT_APIKEY
        sed -i "/^VENDORS_DB.*/a PIALERT_APIKEY = '$PIA_APIKEY_RAND'" $PIA_CONF_FILE
    else
        ## Change PIALERT_APIKEY
        sed -i "/PIALERT_APIKEY/c\PIALERT_APIKEY = '$PIA_APIKEY_RAND'" $PIA_CONF_FILE
    fi
    echo "API-Key set"
    ;;

  set_permissions)
    ## Set file permissions
    # get username from install directory
    PIA_USER=$(echo ${SCRIPTPATH} | xargs dirname | xargs dirname | xargs basename)
    echo "Pi.Alert User: $PIA_USER"
    sudo chown ${PIA_USER}:www-data $PIA_DB_FILE
    sudo chmod -R 770 $PIA_DB_FILE
    echo "Permissions set"
    ;;

  set_sudoers)
    ## Set file permissions
    # get username from install directory
    PIA_USER=$(echo ${SCRIPTPATH} | xargs dirname | xargs dirname | xargs basename)
    echo "Pi.Alert User: $PIA_USER"
    echo -e "\nFrontend sudoer"
    echo "www-data ALL=(ALL) NOPASSWD: ${SCRIPTPATH}/pialert-cli" | sudo tee /etc/sudoers.d/pialert-frontend
    echo -e "\nBackend sudoer"
    echo "${PIA_USER} ALL=(ALL) NOPASSWD: ${SCRIPTPATH}/pialert-cli" | sudo tee /etc/sudoers.d/pialert-backend
    echo "${PIA_USER} ALL=(ALL) NOPASSWD: /usr/sbin/arp-scan" | sudo tee /etc/sudoers.d/pialert-backend
    echo "${PIA_USER} ALL=(ALL) NOPASSWD: /usr/bin/nmap" | sudo tee /etc/sudoers.d/pialert-backend
    ;;

  unset_sudoers)
    ## Set file permissions
    # get username from install directory
    PIA_USER=$(echo ${SCRIPTPATH} | xargs dirname | xargs dirname | xargs basename)
    echo "Removing sudoers"
    sudo rm /etc/sudoers.d/pialert-frontend
    sudo rm /etc/sudoers.d/pialert-backend
    ;;

  reporting_test)
    ## test reporting
    /usr/bin/python3 ${SCRIPTPATH}/pialert.py reporting_test
    echo "Test executed"
    ;;

  rewrite_config)
    # Input file
    input_file=$PIA_CONF_FILE
    echo "    The existing configuration will not be replaced."
    echo "    Only a new decluttered configuration file (pialert-rewritten.conf) is created."

    # Get Value from config file
    # -------------------------------------------------------------------------------
    # General
    REWRITE_PIALERT_PATH=$(grep "^PIALERT_PATH" $input_file)
    REWRITE_DB_PATH=$(grep "^DB_PATH" $input_file)
    REWRITE_LOG_PATH=$(grep "^LOG_PATH" $input_file)
    REWRITE_PRINT_LOG=$(grep "^PRINT_LOG" $input_file)
    REWRITE_VENDORS_DB=$(grep "^VENDORS_DB" $input_file)
    REWRITE_PIALERT_WEB_PROTECTION=$(grep "^PIALERT_WEB_PROTECTION" $input_file)
    REWRITE_PIALERT_WEB_PASSWORD=$(grep "^PIALERT_WEB_PASSWORD" $input_file)
    REWRITE_SCAN_WEBSERVICES=$(grep "^SCAN_WEBSERVICES" $input_file)
    # Special Protocol Scanning
    REWRITE_SCAN_ROGUE_DHCP=$(grep "^SCAN_ROGUE_DHCP" $input_file)
    REWRITE_DHCP_SERVER_ADDRESS=$(grep "^DHCP_SERVER_ADDRESS" $input_file)
    # Mail-Account Settings
    REWRITE_SMTP_SERVER=$(grep "^SMTP_SERVER" $input_file)
    REWRITE_SMTP_PORT=$(grep "^SMTP_PORT" $input_file)
    REWRITE_SMTP_USER=$(grep "^SMTP_USER" $input_file)
    REWRITE_SMTP_PASS=$(grep "^SMTP_PASS" $input_file)
    REWRITE_SMTP_SKIP_TLS=$(grep "^SMTP_SKIP_TLS" $input_file)
    REWRITE_SMTP_SKIP_LOGIN=$(grep "^SMTP_SKIP_LOGIN" $input_file)
    # WebGUI Reporting
    REWRITE_REPORT_WEBGUI=$(grep "^REPORT_WEBGUI " $input_file)
    REWRITE_REPORT_WEBGUI_WEBMON=$(grep "^REPORT_WEBGUI_WEBMON" $input_file)
    # Mail Reporting
    REWRITE_REPORT_MAIL=$(grep "^REPORT_MAIL " $input_file)
    REWRITE_REPORT_MAIL_WEBMON=$(grep "^REPORT_MAIL_WEBMON" $input_file)
    REWRITE_REPORT_FROM=$(grep "^REPORT_FROM" $input_file)
    REWRITE_REPORT_TO=$(grep "^REPORT_TO" $input_file)
    REWRITE_REPORT_DEVICE_URL=$(grep "^REPORT_DEVICE_URL" $input_file)
    REWRITE_REPORT_DASHBOARD_URL=$(grep "^REPORT_DASHBOARD_URL" $input_file)
    # Pushsafer
    REWRITE_REPORT_PUSHSAFER=$(grep "^REPORT_PUSHSAFER " $input_file)
    REWRITE_REPORT_PUSHSAFER_WEBMON=$(grep "^REPORT_PUSHSAFER_WEBMON" $input_file)
    REWRITE_PUSHSAFER_TOKEN=$(grep "^PUSHSAFER_TOKEN" $input_file)
    REWRITE_PUSHSAFER_DEVICE=$(grep "^PUSHSAFER_DEVICE" $input_file)
    # Pushover
    REWRITE_REPORT_PUSHOVER=$(grep "^REPORT_PUSHOVER " $input_file)
    REWRITE_REPORT_PUSHOVER_WEBMON=$(grep "^REPORT_PUSHOVER_WEBMON" $input_file)
    REWRITE_PUSHOVER_TOKEN=$(grep "^PUSHOVER_TOKEN" $input_file)
    REWRITE_PUSHOVER_USER=$(grep "^PUSHOVER_USER" $input_file)
    # ntfy
    REWRITE_REPORT_NTFY=$(grep "^REPORT_NTFY " $input_file)
    REWRITE_REPORT_NTFY_WEBMON=$(grep "^REPORT_NTFY_WEBMON" $input_file)
    REWRITE_NTFY_HOST=$(grep "^NTFY_HOST" $input_file)
    REWRITE_NTFY_TOPIC=$(grep "^NTFY_TOPIC" $input_file)
    REWRITE_NTFY_USER=$(grep "^NTFY_USER" $input_file)
    REWRITE_NTFY_PASSWORD=$(grep "^NTFY_PASSWORD" $input_file)
    REWRITE_NTFY_PRIORITY=$(grep "^NTFY_PRIORITY" $input_file)
    # Shoutrrr
    REWRITE_SHOUTRRR_BINARY=$(grep "^SHOUTRRR_BINARY" $input_file)
    # Telegram via Shoutrrr
    REWRITE_REPORT_TELEGRAM=$(grep "^REPORT_TELEGRAM " $input_file)
    REWRITE_REPORT_TELEGRAM_WEBMON=$(grep "^REPORT_TELEGRAM_WEBMON" $input_file)
    REWRITE_TELEGRAM_BOT_TOKEN_URL=$(grep "^TELEGRAM_BOT_TOKEN_URL" $input_file)
    # DynDNS
    REWRITE_QUERY_MYIP_SERVER=$(grep "^QUERY_MYIP_SERVER" $input_file)
    REWRITE_DDNS_ACTIVE=$(grep "^DDNS_ACTIVE" $input_file)
    REWRITE_DDNS_DOMAIN=$(grep "^DDNS_DOMAIN" $input_file)
    REWRITE_DDNS_USER=$(grep "^DDNS_USER" $input_file)
    REWRITE_DDNS_PASSWORD=$(grep "^DDNS_PASSWORD" $input_file)
    REWRITE_DDNS_UPDATE_URL=$(grep "^DDNS_UPDATE_URL" $input_file)
    # Pi-hole Configuration
    REWRITE_PIHOLE_ACTIVE=$(grep "^PIHOLE_ACTIVE" $input_file)
    REWRITE_PIHOLE_DB=$(grep "^PIHOLE_DB" $input_file)
    REWRITE_DHCP_ACTIVE=$(grep "^DHCP_ACTIVE" $input_file)
    REWRITE_DHCP_LEASES=$(grep "^DHCP_LEASES" $input_file)
    # Fritzbox Configuration
    REWRITE_FRITZBOX_ACTIVE=$(grep "^FRITZBOX_ACTIVE" $input_file)
    REWRITE_FRITZBOX_IP=$(grep "^FRITZBOX_IP" $input_file)
    REWRITE_FRITZBOX_USER=$(grep "^FRITZBOX_USER" $input_file)
    REWRITE_FRITZBOX_PASS=$(grep "^FRITZBOX_PASS" $input_file)
    # Maintenance Tasks Cron
    REWRITE_DAYS_TO_KEEP_ONLINEHISTORY=$(grep "^DAYS_TO_KEEP_ONLINEHISTORY" $input_file)
    REWRITE_DAYS_TO_KEEP_EVENTS=$(grep "^DAYS_TO_KEEP_EVENTS" $input_file)
    # Arp-scan Options & Samples
    REWRITE_MAC_IGNORE_LIST=$(grep "^MAC_IGNORE_LIST" $input_file)
    REWRITE_SCAN_SUBNETS=$(grep "^SCAN_SUBNETS" $input_file)

    # Set defaults if empty
    # -------------------------------------------------------------------------------
    # General Settings
    if [ -z "$REWRITE_PIALERT_WEB_PROTECTION" ]
    then
        REWRITE_PIALERT_WEB_PROTECTION="PIALERT_WEB_PROTECTION = False"
    fi
    if [ -z "$REWRITE_PIALERT_WEB_PASSWORD" ]
    then
        REWRITE_PIALERT_WEB_PASSWORD="PIALERT_WEB_PASSWORD   = '8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92'"
    fi
    if [ -z "$REWRITE_SCAN_WEBSERVICES" ]
    then
        REWRITE_SCAN_WEBSERVICES="SCAN_WEBSERVICES       = True"
    fi

    # Special Protocol Scanning
    if [ -z "$REWRITE_SCAN_ROGUE_DHCP" ]
    then
        REWRITE_SCAN_ROGUE_DHCP="SCAN_ROGUE_DHCP        = False"
    fi
    if [ -z "$REWRITE_DHCP_SERVER_ADDRESS" ]
    then
        REWRITE_DHCP_SERVER_ADDRESS="DHCP_SERVER_ADDRESS    = '0.0.0.0'"
    fi

    # WebGUI Reporting
    if [ -z "$REWRITE_REPORT_WEBGUI" ]
    then
        REWRITE_REPORT_WEBGUI="REPORT_WEBGUI         = True"
    fi
    if [ -z "$REWRITE_REPORT_WEBGUI_WEBMON" ]
    then
        REWRITE_REPORT_WEBGUI_WEBMON="REPORT_WEBGUI_WEBMON  = True"
    fi

    # ntfy
    if [ -z "$REWRITE_REPORT_NTFY" ]
    then
        REWRITE_REPORT_NTFY="REPORT_NTFY         = False"
    fi
    if [ -z "$REWRITE_REPORT_NTFY_WEBMON" ]
    then
        REWRITE_REPORT_NTFY_WEBMON="REPORT_NTFY_WEBMON  = False"
    fi
    if [ -z "$REWRITE_NTFY_HOST" ]
    then
        REWRITE_NTFY_HOST="NTFY_HOST           = 'https://ntfy.sh'"
    fi
    if [ -z "$REWRITE_NTFY_TOPIC" ]
    then
        REWRITE_NTFY_TOPIC="NTFY_TOPIC          = 'replace_my_secure_topicname_91h889f28'"
    fi
    if [ -z "$REWRITE_NTFY_USER" ]
    then
        REWRITE_NTFY_USER="NTFY_USER           = 'user'"
    fi
    if [ -z "$REWRITE_NTFY_PASSWORD" ]
    then
        REWRITE_NTFY_PASSWORD="NTFY_PASSWORD        = 'password'"
    fi
    if [ -z "$REWRITE_NTFY_PRIORITY" ]
    then
        REWRITE_NTFY_PRIORITY="NTFY_PRIORITY        = 'default'"
    fi

    # Fritzbox Configuration
    if [ -z "$REWRITE_FRITZBOX_ACTIVE" ]
    then
        REWRITE_FRITZBOX_ACTIVE="FRITZBOX_ACTIVE   = False"
    fi
    if [ -z "$REWRITE_FRITZBOX_IP" ]
    then
        REWRITE_FRITZBOX_IP="FRITZBOX_IP       = '192.168.17.1'"
    fi
    if [ -z "$REWRITE_FRITZBOX_USER" ]
    then
        REWRITE_FRITZBOX_USER="FRITZBOX_USER     = 'user'"
    fi
    if [ -z "$REWRITE_FRITZBOX_PASS" ]
    then
        REWRITE_FRITZBOX_PASS="FRITZBOX_PASS     = 'password'"
    fi

    if [ -z "$REWRITE_MAC_IGNORE_LIST" ]
    then
        REWRITE_MAC_IGNORE_LIST="#MAC_IGNORE_LIST = ['11:22:33:aa:bb:cc']"
    fi

    # Write clean Config
    # -------------------------------------------------------------------------------
    cat >$PIA_CONF_FILE_PATH/pialert-rewritten.conf <<EOL
# General Settings
# ----------------------
${REWRITE_PIALERT_PATH}
${REWRITE_DB_PATH}
${REWRITE_LOG_PATH}
${REWRITE_PRINT_LOG}
${REWRITE_VENDORS_DB}
${REWRITE_PIALERT_WEB_PROTECTION}
${REWRITE_PIALERT_WEB_PASSWORD}
${REWRITE_SCAN_WEBSERVICES}

# Special Protocol Scanning
# ----------------------
${REWRITE_SCAN_ROGUE_DHCP}
${REWRITE_DHCP_SERVER_ADDRESS}

# Mail-Account Settings
# ----------------------
${REWRITE_SMTP_SERVER}
${REWRITE_SMTP_PORT}
${REWRITE_SMTP_USER}
${REWRITE_SMTP_PASS}
${REWRITE_SMTP_SKIP_TLS}
${REWRITE_SMTP_SKIP_LOGIN}

# WebGUI Reporting
# ----------------------
${REWRITE_REPORT_WEBGUI}
${REWRITE_REPORT_WEBGUI_WEBMON}

# Mail Reporting
# ----------------------
${REWRITE_REPORT_MAIL}
${REWRITE_REPORT_MAIL_WEBMON}
${REWRITE_REPORT_FROM}
${REWRITE_REPORT_TO}
${REWRITE_REPORT_DEVICE_URL}
${REWRITE_REPORT_DASHBOARD_URL}

# Pushsafer
# ----------------------
${REWRITE_REPORT_PUSHSAFER}
${REWRITE_REPORT_PUSHSAFER_WEBMON}
${REWRITE_PUSHSAFER_TOKEN}
${REWRITE_PUSHSAFER_DEVICE}

# Pushover
# ----------------------
${REWRITE_REPORT_PUSHOVER}
${REWRITE_REPORT_PUSHOVER_WEBMON}
${REWRITE_PUSHOVER_TOKEN}
${REWRITE_PUSHOVER_USER}

# ntfy
# ----------------------
${REWRITE_REPORT_NTFY}
${REWRITE_REPORT_NTFY_WEBMON}
${REWRITE_NTFY_HOST}
${REWRITE_NTFY_TOPIC}
${REWRITE_NTFY_USER}
${REWRITE_NTFY_PASSWORD}
${REWRITE_NTFY_PRIORITY}

# Shoutrrr
# ----------------------
${REWRITE_SHOUTRRR_BINARY}
# SHOUTRRR_BINARY    = 'armhf'
# SHOUTRRR_BINARY    = 'arm64'
# SHOUTRRR_BINARY    = 'x86'

# Telegram via Shoutrrr
# ----------------------
${REWRITE_REPORT_TELEGRAM}
${REWRITE_REPORT_TELEGRAM_WEBMON}
${REWRITE_TELEGRAM_BOT_TOKEN_URL}

# DynDNS
# ----------------------
${REWRITE_QUERY_MYIP_SERVER}
${REWRITE_DDNS_ACTIVE}
${REWRITE_DDNS_DOMAIN}
${REWRITE_DDNS_USER}
${REWRITE_DDNS_PASSWORD}
${REWRITE_DDNS_UPDATE_URL}

# Pi-hole Configuration
# ----------------------
${REWRITE_PIHOLE_ACTIVE}
${REWRITE_PIHOLE_DB}
${REWRITE_DHCP_ACTIVE}
${REWRITE_DHCP_LEASES}

# Fritzbox Configuration
# ----------------------
${REWRITE_FRITZBOX_ACTIVE}
${REWRITE_FRITZBOX_IP}
${REWRITE_FRITZBOX_USER}
${REWRITE_FRITZBOX_PASS}

# Maintenance Tasks Cron
# ----------------------
${REWRITE_DAYS_TO_KEEP_ONLINEHISTORY}
${REWRITE_DAYS_TO_KEEP_EVENTS}

# Arp-scan Options & Samples
# ----------------------
${REWRITE_MAC_IGNORE_LIST}
${REWRITE_SCAN_SUBNETS}
# SCAN_SUBNETS    = '--localnet'
# SCAN_SUBNETS    = '--localnet --interface=eth0'
# SCAN_SUBNETS    = [ '192.168.1.0/24 --interface=eth0', '192.168.2.0/24 --interface=eth1' ]

EOL
    ;;

    arg_list)
      echo disable_scan disable_service_mon enable_scan enable_service_mon reporting_test rewrite_config set_apikey set_autopassword set_login set_password set_permissions set_sudoers unset_login unset_sudoers update_db
    ;;

  *)
    echo "pialert-cli $SCRIPTVERSION (https://github.com/leiweibau/Pi.Alert)"
    echo "Use \"${bold}pialert-cli help${normal}\" for a list of supported commands."
esac

