#!/bin/bash
# This script installs the AppSentinels Edge Controller service on Ubuntu, Amazon Linux and RHEL/CentOS.
# It checks for the presence of Docker and Podman, installs Docker if necessary (removes podman),
# and creates a systemd service for the AppSentinels Edge Controller.
# Copyright (c) AppSentinels. All rights reserved.

echo "Installing AppSentinels Edge Controller..."

# Define mandatory environment variables
CONTAINER_NAME="appsentinels-edge-controller"   #input needed here
HOSTNAME=$(hostname)                            #input needed here, needs to be unique across all the edge controllers
APPLICATION_DOMAIN="<your app domain>"          #input needed here , probably something to denote a bunch of apps
ENVIRONMENT="prod"                              #input needed here, what is the current environment, qa vs prod vs dev etc
SAAS_SERVER_NAME="<your allocated saas server>" #input needed here
SAAS_API_KEY_VALUE=<your provided api key>      #input needed here
CONTAINER_PORT_MAPPING="9004:9004"              #input needed here, default for merged logs, but will depend on sensor
                                                #     9002:9002 for req and resp logging sensors like envoy
                                                #     9004:9004 for merged log sensors (eg: kong, lambda, sniffer)
                                                #     9006:9006 for req and resp logging sensors (eg: nginx, apigee)
CPU_SHARES="0.00"                               #input needed here, fix this valid limit else set to to 0.00
MEMORY="0g"                                     #input needed here, fix this to valid limit else set to 0g
HTTPS_INSECURE_SKIP_VERIFY="false"              #input needed here, set to true if using self signed certs for SAAS

# Function to install Docker
install_docker() {
    echo "Docker not found. Installing Docker..."
    case $1 in
        ubuntu|debian)
            apt-get update
            apt-get install -y docker.io
            ;;
        rhel|centos)
            # Later versions need podman, need to confirm
            yum remove podman -y
            yum install -y yum-utils
            yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
            yum install docker-ce docker-ce-cli containerd.io -y

            systemctl start docker
            systemctl enable docker
            ;;
        amzn)
            yum update -y
            amazon-linux-extras install docker -y

            systemctl start docker
            systemctl enable docker
            ;;   
        *)
            echo "Unsupported OS: $1"
            exit 1
            ;;
    esac
}

# Detect the Linux distribution
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$ID
else
    echo "Cannot detect OS. Exiting."
    exit 1
fi

# Install Docker if not already installed
if ! command -v docker &> /dev/null; then
    install_docker $OS
else
    # Check if Podman is also installed, its symlink to docker usually on redhat
    if command -v podman &> /dev/null; then
        echo "Podman is installed. Removing and reinstalling Docker..."
        install_docker $OS
    else
        echo "Docker is already installed."
    fi
fi


IMAGE_TAG="latest"

# Check if the service file exists
if [ -f /etc/systemd/system/appsentinels-edge-controller.service ]; then
    echo "AppSentinels Edge Controller service file already exists."
else
    # Create systemd service file
    tee /etc/systemd/system/appsentinels-edge-controller.service > /dev/null << EOF
[Unit]
Description=AppSentinels Edge Controller Service
After=docker.service
Requires=docker.service

[Service]
Restart=always
RestartSec=10
ExecStartPre=/bin/sh -c '/usr/bin/docker stop $CONTAINER_NAME || true'
ExecStartPre=/bin/sh -c '/usr/bin/docker rm $CONTAINER_NAME || true'
ExecStart=/usr/bin/docker run --name $CONTAINER_NAME --hostname $HOSTNAME \
  --env APPLICATION_DOMAIN=$APPLICATION_DOMAIN \
  --env ENVIRONMENT=$ENVIRONMENT \
  --env SAAS_SERVER_NAME=$SAAS_SERVER_NAME \
  --env SAAS_API_KEY_VALUE=$SAAS_API_KEY_VALUE \
  -p $CONTAINER_PORT_MAPPING \
  --cpus=$CPU_SHARES \
  --memory=$MEMORY \
  --log-driver local --log-opt max-size=10m \
  appsentinels/ng-controller:$IMAGE_TAG
ExecStop=/usr/bin/docker stop $CONTAINER_NAME
ExecStop=/usr/bin/docker rm $CONTAINER_NAME

[Install]
WantedBy=multi-user.target
EOF
    echo "AppSentinels Edge Controller service file created."
fi

# Reload systemd daemon
systemctl daemon-reload

# Enable and start the service
systemctl enable appsentinels-edge-controller
systemctl start appsentinels-edge-controller

echo "AppSentinels Edge Controller service installed and started successfully."

