#!/bin/bash
source /etc/profile.d/red[bB]order-manager.sh
##########  Variable Declarations - Start  ##########
#name of the current script
SCRIPT_NAME=configure-checkpoint.sh
#version of the current script
SCRIPT_VERSION=1.0

LOGSTASH_ETCDIR_CONF=$LOGSTASH_PIPELINES_PATH/vault

#name of the service, in this case checkpoint
SERVICE="checkpoint"

RB_PATH=${RB_PATH:=""}
RB_EXTENSIONS_DIR="$RB_PATH/var/rb-extensions"

#name and location of checkpoint logstash file
LOGSTASH_CONFFILE=$LOGSTASH_ETCDIR_CONF/28_checkpoint.conf

MANUAL_CONFIG_INSTRUCTION="Manual instructions to configure checkpoint is available at https://suport.redborder.com/docs/checkpoint-server-logs#manual. Logstash troubleshooting instructions are available at https://support.redborder.com/docs/troubleshooting-logstash/"

INSTALLED_FILE=$EXTENSION_DIR/extension-installed.txt

##########  Variable Declarations - End  ##########

##########  Qradar Functions  - Start   ###########

#function to write the contents of  logstash config file

writeFileContents()
{
  echo "INFO" "INFO: Creating file $LOGSTASH_CONFFILE"
  sudo touch $LOGSTASH_CONFFILE
  sudo chmod o+w $LOGSTASH_CONFFILE

        if [ ! -f $DIMENSIONS_CONFFILE ]; then
          echo "cannot find the dimension file to setup the logstash pipeline. exiting..."
          exit 1
        fi

        # build the array of original dimensions
ORIG_DIM=$(
ruby - <<END
  require 'yaml'
  original_dimensions = []
  dimensions = {}
  dimensions = dimensions.merge(YAML.load_file("$DIMENSIONS_CONFFILE"))
  dimensions.each { | key, dimension | original_dimensions.push(dimension['original_dimension']) }
  puts original_dimensions.to_s
END
)

  imfileStr="filter {

    if \"CheckPoint\" in [raw-message] {

  ruby {
    code => '
           require \"json\"
           require \"yaml\"
           dimensions = {}
           original_dimensions = []
           dimensions = dimensions.merge(YAML.load_file(\"$DIMENSIONS_CONFFILE\"))
           jsondata = event.get(\"[structured_data]\")
           jsondata = \"{\" + jsondata.split(\"[\",2).last.to_s
           jsondata = jsondata[0...-4]
	       jsondata = jsondata.gsub(/;/,\",\")
           jsondata = jsondata.gsub(/\w+:/) { \"\\\"#{$&}\\\"\" }
           jsondata = jsondata.gsub(/:\\\"/, \"\\\":\")         
           jsondata = jsondata.tr(\"\\\\\",\"\") + \"\\\"}\".tr(\"=>\",\":\")
           jsondata = JSON.parse(jsondata)
           jsondata.each { |key, value|
                   puts key
                   event.set(\"${SERVICE}_\"+key,value) if ${ORIG_DIM}.include? key
                }

        '
  }
  mutate{
  remove_field => [\"raw-message\",\"@version\",\"structured_data\",\"@timestamp\"]

  }
 }
}
"
	
  
  
  #change the checkpoint-28 file to variable from above and also take the directory of the checkpoint log file.
sudo cat << EOIPFW > $LOGSTASH_CONFFILE
$imfileStr
EOIPFW

  restartLogstash
}



#function to write the contents of checkpoint logstash config file
writeDimensionsFile()
{
  echo "INFO: Creating dimensions file $DIMENSIONS_CONFFILE"
  sudo touch $DIMENSIONS_CONFFILE
  sudo chmod o+w $DIMENSIONS_CONFFILE
         
imfileStr=$SERVICE'_flags:
  name: "flags"
  category: "checkpoint"
  type: string
  original_dimension: "flags"
'$SERVICE'_ifdir:
  name: "ifdir"
  category: "checkpoint"
  type: string
  original_dimension: "ifdir"
#'$SERVICE'_logid:
#  name: "logid"
#  category: "checkpoint"
#  type: string
#  original_dimension: "logid"
#'$SERVICE'_loguid:
#  name: "loguid"
#  category: "checkpoint"
#  type: string
#  original_dimension: "loguid"
'$SERVICE'_origin:
  name: "origin"
  category: "checkpoint"
  type: string
  original_dimension: "origin"
#'$SERVICE'_sequencenum:
#  name: "sequencenum"
#  category: "checkpoint"
#  type: string
#  original_dimension: "sequencenum"
#'$SERVICE'_time:
#  name: "time"
#  category: "checkpoint"
#  type: string
#  original_dimension: "time"
#'$SERVICE'_version:
#  name: "version"
#  category: "checkpoint"
#  type: string
#  original_dimension: "version"
#'$SERVICE'_cu_detected_by:
#  name: "cu_detected_by"
#  category: "checkpoint"
#  type: string
#  original_dimension: "cu_detected_by"
#'$SERVICE'_cu_detection_time:
#  name: "cu_detection_time"
#  category: "checkpoint"
#  type: string
#  original_dimension: "cu_detection_time"
#'$SERVICE'_cu_last_update_time:
#  name: "cu_last_update_time"
#  category: "checkpoint"
#  type: string
#  original_dimension: "cu_last_update_time"
#'$SERVICE'_cu_log_count:
#  name: "cu_log_count"
#  category: "checkpoint"
#  type: string
#  original_dimension: "cu_log_count"
#'$SERVICE'_cu_rule_category:
#  name: "cu_rule_category"
#  category: "checkpoint"
#  type: string
#  original_dimension: "cu_rule_category"
#'$SERVICE'_cu_rule_id:
#  name: "cu_rule_id"
#  category: "checkpoint"
#  type: string
#  original_dimension: "cu_rule_id"
'$SERVICE'_domain:
  name: "domain"
  category: "checkpoint"
  type: string
  original_dimension: "domain"
#'$SERVICE'_event_start_time:
#  name: "event_start_time"
#  category: "checkpoint"
#  type: string
#  original_dimension: "event_start_time"
#'$SERVICE'_is_correlated:
#  name: "is_correlated"
#  category: "checkpoint"
#  type: string
#  original_dimension: "is_correlated"
#'$SERVICE'_log_id:
#  name: "log_id"
#  category: "checkpoint"
#  type: string
#  original_dimension: "log_id"
#'$SERVICE'_max_num_count_detected:
#  name: "max_num_count_detected"
#  category: "checkpoint"
#  type: string
#  original_dimension: "max_num_count_detected"
#'$SERVICE'_num_of_updates:
#  name: "num_of_updates"
#  category: "checkpoint"
#  type: string
#  original_dimension: "num_of_updates"
#'$SERVICE'_origin_repetitions:
#  name: "origin_repetitions"
#  category: "checkpoint"
#  type: string
#  original_dimension: "origin_repetitions"
'$SERVICE'_product:
  name: "product"
  category: "checkpoint"
  type: string
  original_dimension: "product"
#'$SERVICE'_sensor_alert_category:
#  name: "sensor_alert_category"
#  category: "checkpoint"
#  type: string
#  original_dimension: "sensor_alert_category"
#'$SERVICE'_sensor_alert_id:
#  name: "sensor_alert_id"
#  category: "checkpoint"
#  type: string
#  original_dimension: "sensor_alert_id"
#'$SERVICE'_sensor_alert_message:
#  name: "sensor_alert_message"
#  category: "checkpoint"
#  type: string
#  original_dimension: "sensor_alert_message"
#'$SERVICE'_sensor_alert_module:
#  name: "sensor_alert_module"
#  category: "checkpoint"
#  type: string
#  original_dimension: "sensor_alert_module"
#'$SERVICE'_sensor_alert_title:
#  name: "sensor_alert_title"
#  category: "checkpoint"
#  type: string
#  original_dimension: "sensor_alert_title"
#'$SERVICE'_sensor_alert_type:
#  name: "sensor_alert_type"
#  category: "checkpoint"
#  type: string
#  original_dimension: "sensor_alert_type"
#'$SERVICE'_sensor_test_name:
#  name: "sensor_test_name"
#  category: "checkpoint"
#  type: string
#  original_dimension: "sensor_test_name"
#'$SERVICE'_time_interval:
#  name: "time_interval"
#  category: "checkpoint"
#  type: string
#  original_dimension: "time_interval"
'$SERVICE'_ifname:
  name: "ifname"
  category: "checkpoint"
  type: string
  original_dimension: "ifname"
#'$SERVICE'_originsicname:
#  name: "originsicname"
#  category: "checkpoint"
#  type: string
#  original_dimension: "originsicname"
#'$SERVICE'_policy_id_tag:
#  name: "policy_id_tag"
#  category: "checkpoint"
#  type: string
#  original_dimension: "policy_id_tag"
#'$SERVICE'_date:
#  name: "date"
#  category: "checkpoint"
#  type: string
#  original_dimension: "date"
#'$SERVICE'_policy_name:
#  name: "policy_name"
#  category: "checkpoint"
#  type: string
#  original_dimension: "policy_name"
'$SERVICE'_dst:
  name: "dst"
  category: "checkpoint"
  type: string
  original_dimension: "dst"
#'$SERVICE'_inzone:
#  name: "inzone"
#  category: "checkpoint"
#  type: string
#  original_dimension: "inzone"
'$SERVICE'_layer_name:
  name: "layer_name"
  category: "checkpoint"
  type: string
  original_dimension: "layer_name"
#'$SERVICE'_layer_uuid:
#  name: "layer_uuid"
#  category: "checkpoint"
#  type: string
#  original_dimension: "layer_uuid"
#'$SERVICE'_match_id:
#  name: "match_id"
#  category: "checkpoint"
#  type: string
#  original_dimension: "match_id"
#'$SERVICE'_parent_rule:
#  name: "parent_rule"
#  category: "checkpoint"
#  type: string
#  original_dimension: "parent_rule"
'$SERVICE'_rule_action:
  name: "rule_action"
  category: "checkpoint"
  type: string
  original_dimension: "rule_action"
'$SERVICE'_rule_name:
  name: "rule_name"
  category: "checkpoint"
  type: string
  original_dimension: "rule_name"
#'$SERVICE'_rule_uid:
#  name: "rule_uid"
#  category: "checkpoint"
#  type: string
#  original_dimension: "rule_uid"
#'$SERVICE'_outzone:
#  name: "outzone"
#  category: "checkpoint"
#  type: string
#  original_dimension: "outzone"
'$SERVICE'_protocol:
  name: "protocol"
  category: "checkpoint"
  type: string
  original_dimension: "protocol"
'$SERVICE'_s_port:
  name: "s_port"
  category: "checkpoint"
  type: string
  original_dimension: "s_port"
#'$SERVICE'_service:
#  name: "service"
#  category: "checkpoint"
#  type: string
#  original_dimension: "service"
'$SERVICE'_service_id:
  name: "service_id"
  category: "checkpoint"
  type: string
  original_dimension: "service_id"
'$SERVICE'_src:
  name: "src"
  category: "checkpoint"
  type: string
  original_dimension: "src"
#'$SERVICE'_conn_direction:
#  name: "conn_direction"
#  category: "checkpoint"
#  type: string
#  original_dimension: "conn_direction"
#'$SERVICE'_contextnum:
#  name: "contextnum"
#  category: "checkpoint"
#  type: string
#  original_dimension: "contextnum"
#'$SERVICE'_mgmt:
#  name: "mgmt"
#  category: "checkpoint"
#  type: string
#  original_dimension: "mgmt"
#'$SERVICE'_context_num:
#  name: "context_num"
#  category: "checkpoint"
#  type: string
#  original_dimension: "context_num"
#'$SERVICE'_hll_key:
#  name: "hll_key"
#  category: "checkpoint"
#  type: string
#  original_dimension: "hll_key"
#'$SERVICE'_nat_addtnl_rulenum:
#  name: "nat_addtnl_rulenum"
#  category: "checkpoint"
#  type: string
#  original_dimension: "nat_addtnl_rulenum"
#'$SERVICE'_nat_rulenum:
#  name: "nat_rulenum"
#  category: "checkpoint"
#  type: string
#  original_dimension: "nat_rulenum"
#'$SERVICE'_protocolID:
#  name: "protocolID"
#  category: "checkpoint"
#  type: string
#  original_dimension: "protocolID"
#'$SERVICE'_sig_id:
#  name: "sig_id"
#  category: "checkpoint"
#  type: string
#  original_dimension: "sig_id"
#'$SERVICE'_xlatedport:
#  name: "xlatedport"
#  category: "checkpoint"
#  type: string
#  original_dimension: "xlatedport"
#'$SERVICE'_xlatedst:
#  name: "xlatedst"
#  category: "checkpoint"
#  type: string
#  original_dimension: "xlatedst"
#'$SERVICE'_xlatesport:
#  name: "xlatesport"
#  category: "checkpoint"
#  type: string
#  original_dimension: "xlatesport"
#'$SERVICE'_xlatesrc:
#  name: "xlatesrc"
#  category: "checkpoint"
#  type: string
#  original_dimension: "xlatesrc"'

sudo cat << EOIPFW > $DIMENSIONS_CONFFILE
$imfileStr
EOIPFW
  
}

##########  Checkpoint Functions  - End   ###########


##########  Start of the common part  ###########


#downloads configure-extensions.sh
setupDependencies() {
  ERROR="true"
  # Check if there is internet or/and can access to the web of the script
  response=$(curl --write-out %{http_code} --silent --output /dev/null https://repo.redborder.com/install/common/configure-extensions.sh)
  if [[ $response -eq 200 ]]; then
    echo "INFO: Downloading dependencies.."
    curl -s -o configure-extensions.sh https://repo.redborder.com/install/common/configure-extensions.sh
  else
    echo "configure-extensions script could not be retrieved, local copy is needed"
  fi
  
  if [ -f configure-extensions.sh ]; then
    if [ `head -1 configure-extensions.sh | grep bash | wc -l` -gt 0 ]; then
      source configure-extensions.sh "being-invoked"

      #definitions of variables relying on the configure-extensions-script
      EXTENSION_DIR=$RB_EXTENSIONS_DIR/$SERVICE
      DIMENSIONS_CONFFILE=$EXTENSION_DIR/dimensions.yml

      ERROR="false"
    else
      echo "local configure-extensions script is not valid, we need to exit"  
    fi
  fi
  
  if [ "$ERROR" != "false" ]; then
    echo "ERROR: Missing dependencies!"
    exit 1
  fi
}


#display usage syntax
usage()
{
cat << EOF
usage: configure-$SERVICE [-i to install]
usage: configure-$SERVICE [-r to rollback]
usage: configure-$SERVICE [-v for version]
usage: configure-$SERVICE [-u to update]
usage: configure-$SERVICE [-h for help]
EOF
}

##########  Get Inputs from User - Start  ##########

if [ $# -eq 0 ]; then
    usage
  exit
else
while [ "$1" != "" ]; do
    case $1 in
      -r | --rollback )
      REDBORDER_ROLLBACK="true"
          ;;
      -i | --install )
                  #SUPPRESS_PROMPT="true"
                  INSTALL="true"
          ;;    
      -v | --version )
          echo "The version of $SERVICE is $SCRIPT_VERSION, to check for any update use configure-$SERVICE -u"
          exit
          ;;
      -u | --update )
          echo "Checking for updates..."
          UPDATING="true"
          ;;
      -h | --help )
          usage
          exit
          ;;

    esac
    shift
done
fi

if [ "$REDBORDER_ROLLBACK" != "" ]; then
    setupDependencies
    checkIfUserHasRootPrivileges
    removeRedborderConf
elif [ "$INSTALL" == "true" ]; then
    setupDependencies
    checkIfUserHasRootPrivileges
    installRedborderConf
elif [ "$UPDATING" == "true" ]; then
    setupDependencies
    checkIfUserHasRootPrivileges
    checkForUpdate

else
  
    usage
fi

##########  Get Inputs from User - End  ##########

