#!/bin/bash
SCRIPTVERSION='v0.81'
SCRIPT=$(readlink -f $0)
SCRIPTPATH=`dirname $SCRIPT`
PIA_CONF_FILE=${SCRIPTPATH}'/../config/pialert.conf'
PIA_DB_FILE=${SCRIPTPATH}'/../db/pialert.db'
PIA_DB_FILE_PATH=${SCRIPTPATH}'/../db'

case $1 in

  help)
    echo "pialert-cli $SCRIPTVERSION (https://github.com/leiweibau/Pi.Alert)"
    echo "Usage: pialert-cli <command>"
    echo ""
    echo "The is a list of supported commands:"
    echo ""
    echo " set_login                - Sets the parameter PIALERT_WEB_PROTECTION in the config file to TRUE"
    echo "                          - If the parameter is not present, it will be created. Additionally the"
    echo "                            default password '123456' is set."
    echo ""
    echo " unset_login              - Sets the parameter PIALERT_WEB_PROTECTION in the config file to FALSE"
    echo "                          - If the parameter is not present, it will be created. Additionally the"
    echo "                            default password '123456' is set."
    echo ""
    echo " set_password <password>  - Sets the new password as a hashed value."
    echo "                          - If the PIALERT_WEB_PROTECTION parameter does not exist yet, it will be"
    echo "                            created and set to TRUE (login enabled)."
    echo ""
    echo " set_autopassword         - Sets a new random password as a hashed value and show it plaintext in"
    echo "                            the console."
    echo "                          - If the PIALERT_WEB_PROTECTION parameter does not exist yet, it will be"
    echo "                            created and set to TRUE (login enabled)."
    echo ""
    echo " disable_scan <MIN>       - Stops all active scans"
    echo "                          - Prevents new scans from starting."
    echo "                          - You can set a Timeout in minutes. If no timeout is set, Pi.Alert"
    echo "                            restarts itself with the next scan after 10min."
    echo ""
    echo " enable_scan              - Allows the start of new scans again."
    echo ""
    echo " enable_service_mon       - Enable Web Service Monitoring."
    echo "                          - If the SCAN_WEBSERVICES parameter does not exist yet, it will be"
    echo "                            created and set to TRUE."
    echo ""
    echo " disable_service_mon      - Allows the start of new scans again."
    echo "                          - If the SCAN_WEBSERVICES parameter does not exist yet, it will be"
    echo "                            created and set to FALSE."
    echo ""
    echo " update_db                - The script tries to make the database compatible for this fork."
    echo ""
    echo " set_apikey               - With the API key it is possible to make queries to the database"
    echo "                            without using the web page. If an API key already exists, it will be"
    echo "                            replaced."
    echo ""
    echo " reporting_test           - Test reporting for all activated services."
    echo ""
    ;;

  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
    /bin/python3 ${SCRIPTPATH}/pialert.py reporting_starttimer
    echo "The arp-scan is disabled"
    ;;

  enable_scan)
    ## stop active scans
    rm ${SCRIPTPATH}/../db/setting_stoparpscan
    /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 "Create backup before insert new table"
    cp $PIA_DB_FILE ${PIA_DB_FILE_PATH}/pialert.db.bak
    echo "Insert new table 'Online_History' to $PIA_DB_FILE"
    sqlite3 $PIA_DB_FILE "CREATE TABLE 'Online_History' ('Index' INTEGER, 'Scan_Date' TEXT, 'Online_Devices' INTEGER, 'Down_Devices' INTEGER, 'All_Devices' INTEGER, 'Archived_Devices' INTEGER, PRIMARY KEY('Index' AUTOINCREMENT));"
    echo "Insert new table 'network_infrastructure' to $PIA_DB_FILE"
    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));"
    sqlite3 $PIA_DB_FILE "ALTER TABLE 'Devices' ADD 'dev_Infrastructure' INTEGER;"
    sqlite3 $PIA_DB_FILE "ALTER TABLE 'Devices' ADD 'dev_Infrastructure_port' INTEGER;"
    ;;

  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"
    ;;

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

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

