#!/bin/bash
# OSx OSSEC Agent Installer
# Name: osx-agent-installer.sh
# Copyright Atomicorp 2025
# License: Commercial. Unauthorized redistribution prohibited.
# VersioN=2.0

# Variables
PROTOCOL=udp
PORT=1514
ROOT_UID=0
IS_UPDATE=0
ARCH=$(arch)
GROUP="default"


#####################
# Functions
#####################
usage_menu () {
  echo "OSx Agent Installer Usage"
  echo "Usage: osx-agent-installer.sh <param>"
  echo "    -h: Shows this message."
  echo
  echo "Mandatory"
  echo "    --server_ip:   IP address of AEO/AWP Hub."
  echo
  echo "Optional"
  echo "    --agent_name: Specify the name to use when registering the agent. [Default: hostname]"
  echo "    --port: Specify the port to register the agent on. [Default: 1514]"
  echo "    --udp/--tcp: Protocol to use to communicate with AEO/AWP Hub. [Default: udp]"
  echo "    --group: Group to assign agent to [Default: default]"
  echo "    --uninstall: Removes the OSSEC agent from this device."
  echo "    --update: Updates the OSSEC agent on this device."
  echo "    --https-enrollment: Use HTTPS enrollment for agent registration."
  echo
}

request_agent_key() {
    server_ip="$1"
    show_msg "Requesting agent key from $server_ip using request_agent_key" log

    if [ -n "$AGENT_NAME" ]; then
        local url="https://${server_ip}:${PORT}/agent_register/?key=none&hostname=${AGENT_NAME}"
    else
        local url="https://${server_ip}:${PORT}/agent_register/?key=none&hostname=$(hostname)"
    fi

    curl -k -o /var/ossec/etc/client.keys.tmp "$url"
    local status=$?

    if [[ $status -eq 0 ]]; then
        echo "Request successful. Response saved to client.keys.tmp"
        awk -F\' '{print $2}' /var/ossec/etc/client.keys.tmp > /var/ossec/etc/client.keys
        return 0
    else
        echo "ERROR: Request failed with status code $status."
        return 1
    fi
}

osx_configure () {
  O_CONF="/var/ossec/etc/ossec.conf"

  # Check if the config file exists
  if [ ! -f "$O_CONF" ]; then
      echo "  ERROR: Configuration file $O_CONF not found!"
      exit 1
  fi

  # Update <server> section
  sed -i '' "s|<address>.*</address>|<address>${SERVER_IP}</address>|g" $O_CONF
  sed -i '' "s|<server>.*<port>[0-9]*</port>|<server>\n    <port>${PORT}</port>|g" $O_CONF
  sed -i '' "s|\(<server>.*\)<protocol>.*</protocol>|\1<protocol>${PROTOCOL}</protocol>|g" "$O_CONF"
  # Update the <enrollment> section
  sed -i '' "s|<manager_address>.*</manager_address>|<manager_address>${SERVER_IP}</manager_address>|g" "$O_CONF"

  # Verify if the changes were applied successfully
  grep -q "<address>${SERVER_IP}</address>" "$O_CONF"
  if [ $? -ne 0 ]; then
      echo "  ERROR: Agent configuration failed!"
      exit 1
  fi

  echo "  INFO: Agent configuration updated successfully."
}



osx_register () {
    if [ "$HTTP_ENROLL" = true ]; then
        request_agent_key ${AUTH_IP}
        if [ $? -ne 0 ]; then
            echo "  ERROR: Failed to register agent using HTTP enrollment"
            exit 1
        fi
    else
        if [ ${AGENT_NAME} ]; then
            /var/ossec/bin/agent-auth -m ${AUTH_IP} -A ${AGENT_NAME} -G ${GROUP}
        else
            /var/ossec/bin/agent-auth -m ${AUTH_IP} -G ${GROUP}
        fi
    fi
}

osx_install() {
  VERSION=$(curl -sk https://${SERVER_IP}/channels/awp-hub-repo/osx/VERSION | grep VERSION | awk -F'=' '{print $2}')
  RELEASE=$(curl -sk https://${SERVER_IP}/channels/awp-hub-repo/osx/VERSION | grep RELEASE | awk -F'=' '{print $2}')
  PACKAGE=ossec-hids-agent-${VERSION}-${RELEASE}.${ARCH}.pkg

  if [ ! -f ${PACKAGE} ]; then
    echo "Downloading  https://${SERVER_IP}/channels/awp-hub-repo/osx/${PACKAGE}... "
    curl -sk https://${SERVER_IP}/channels/awp-hub-repo/osx/${PACKAGE} -O
    echo
  fi

  if  pkgutil --packages | egrep -q atomicorp.ossec.agent ; then
    echo
    echo "    ERROR: ossec-hids-agent installation already detected."
    echo "    exiting ..."
    echo
    exit 1
  fi

  echo "Installing ossec-hids-agent-${PACKAGE}..."
  installer -pkg ${PACKAGE} -target /

  if [ "$?" -ne "0" ]; then
    echo "   ERROR: Installing ${PACKAGE}"
    installer -pkg ${PACKAGE} -target /
    echo "   exiting ..."
    echo
    exit 1
  fi

  echo "VERSION="${VERSION} > /var/ossec/etc/.version
  echo "RELEASE="${RELEASE} >> /var/ossec/etc/.version

  #Configure the agent.
  echo "Configuring ossec-hids-agent ... "
  osx_configure

  #Register the agent.
  echo "Registering agent with manager ${SERVER_IP} "
  osx_register




  #Error handle
  if [ $? -ne 0 ];then
      echo
      echo "  ERROR: agent-auth failed during registration"
      echo "  exiting ..."
      exit 1

  fi


  echo "Restarting agent to finalize installation"
  /var/ossec/bin/ossec-control restart  >/dev/null 2>&1

  if [ "$?" -ne "0" ]; then
    echo "    ERROR: Restarting ossec-hids-agent"
    echo "    exiting ..."
    exit 1
  fi

  echo
  echo "Installation Complete!"
}


################
# Main
################


if [[ $* == *--uninstall* ]]; then
  echo "    INFO: Uninstalling ossec-hids-agent ..."
  pkgutil --forget com.atomicorp.ossec.agent
  rm -rf /var/ossec/
  echo "Complete!"
  echo
  exit 0
fi


while [[ $# -gt 0 ]]; do
  key="$1"

  case $key in
    --server_ip)
      SERVER_IP="$2"
      shift 2
      ;;
    --auth_ip)
      AUTH_IP="$2"
      shift 2
      ;;
    --agent_name)
      AGENT_NAME="$2"
      shift 2
      ;;
    --update)
      IS_UPDATE=1
      shift
      ;;
    --tcp)
      PROTOCOL="tcp"
      shift
      ;;
    --udp)
      PROTOCOL="udp"
      shift
      ;;
    --https-enrollment)
      HTTP_ENROLL="true"
      shift
      ;;
    --group)
      GROUP="$2"
      shift 2
      ;;
    *)
      echo "Unknown option: $1"
      usage_menu
      exit 1
      ;;
  esac
done


if [[ -z "$SERVER_IP" ]]; then
  echo "    ERROR: AEO/AWP Hub IP address was not specified."
  usage_menu
  exit 1
fi


if [ ! ${AUTH_IP} ]; then
  AUTH_IP=$SERVER_IP
fi

if [[ $* == *--tcp* ]]; then
  PROTOCOL=tcp
fi

if [[ $* == *--udp* ]]; then
  PROTOCOL=udp
fi

if [ ! "$UID" ]; then
  UID=$(id -u)
fi

if [ "$UID" -ne "$ROOT_UID" ] ; then
  echo
  echo "    ERROR: You must be root to run this program."
  echo "    exiting..."
  echo
  exit 1
fi

if [[ "$IS_UPDATE" -eq "1" ]]; then
  VERSION=$(curl -s -k https://${SERVER_IP}/channels/awp-hub-repo/osx/VERSION | grep VERSION | awk -F'=' '{print $2}')
  RELEASE=$(curl -s -k https://${SERVER_IP}/channels/awp-hub-repo/osx/VERSION | grep RELEASE | awk -F'=' '{print $2}')

  PACKAGE=ossec-hids-agent-${VERSION}-${RELEASE}.${ARCH}.pkg


  if [ ! -f ${PACKAGE} ]; then
    echo "Downloading https://${SERVER_IP}/channels/awp-hub-repo/osx/${PACKAGE} ... "
    curl -s -kf https://${SERVER_IP}/channels/awp-hub-repo/osx/${PACKAGE} -o ${PACKAGE}
    if [ $? -ne 0 ]; then
      echo "  ERROR:  could not download https://${SERVER_IP}/channels/awp-hub-repo/osx/ossec-hids-agent-${VERSION}-${RELEASE}.pkg"
    fi
    echo
  fi

  cp /var/ossec/etc/ossec.conf .

  echo "Installing ${PACKAGE} ..."
  installer -pkg ossec-hids-agent-${VERSION}-${RELEASE}.pkg -target /

  if [ "$?" -ne "0" ]; then
    echo "   ERROR: Installing ossec-hids-agent-${VERSION}-${RELEASE}.pkg"
    installer -pkg ossec-hids-agent-${VERSION}-${RELEASE}.pkg -target /
    echo "   exiting ..."
    echo
    exit 1
  fi
  echo "VERSION="${VERSION} > /var/ossec/etc/.version
  echo "RELEASE="${RELEASE} >> /var/ossec/etc/.version

  mv ./ossec.conf /var/ossec/etc/ossec.conf

  /var/ossec/bin/ossec-control restart
  echo "Update Complete!"
  exit 0

fi

if [ ! ${AGENT_NAME} ]; then
  echo
  echo "   INFO: Agent name was not detected."
  echo "   Registering agent using default settings."
  echo
fi

osx_install
