#!/bin/bash -e

# Store the directory where bootstrap.sh was initially called from
INITIAL_CWD=$(pwd)

# Change to home directory at the beginning to ensure we can find downloaded files
ORIGINAL_USER=${SUDO_USER:-$(logname)}
ORIGINAL_HOME=$(eval echo ~$ORIGINAL_USER)

# Check if the script is being run from the user's home directory
if [ "$INITIAL_CWD" != "$ORIGINAL_HOME" ]; then
    echo "ERROR: bootstrap.sh should be executed from the non-root user's home directory ($ORIGINAL_HOME)."
    echo "Current working directory is $INITIAL_CWD. Please change directory and re-run."
    exit 1
fi

cd "$ORIGINAL_HOME" || { echo "Failed to change to home directory ($ORIGINAL_HOME)"; exit 1; }

if [ "$S3_PUBLISHER_GENERIC_PATH" = "" ] ; then
    S3_PUBLISHER_GENERIC_PATH=https://files.thepi.es/opcode5
fi

if [ "$#" -ge 1 ] && [ "$1" = "china" ]; then
    touch "$ORIGINAL_HOME/.prc_dp"
fi

HARDENING_SSH=hardening_ssh_yes

function is_rhel {
    [ -f /etc/redhat-release ]
}

function is_bwan {
    [ -d /infroot ]
}

function is_china {
    [ -f "$ORIGINAL_HOME/.prc_dp" ]
}

# wget removed per customer feedback - curl is sufficient and reduces attack surface

function check_existing_container {
    # Check if new_edge_access container is already running
    # Only check if docker/podman is available and running
    if command -v docker &> /dev/null; then
        # Check for containers running the new_edge_access:latest image
        # Note: This works with both Docker and Podman (via podman-docker compatibility)
        local running_containers=$(docker ps --format "{{.Image}}" 2>/dev/null | grep -c "^new_edge_access:latest$" 2>/dev/null || echo "0")
        if [ "$running_containers" -gt 0 ]; then
            echo "Found $running_containers NPA Publisher container(s) already running with image 'new_edge_access:latest'."
            echo "Container details:"
            docker ps --format "table {{.Names}}\t{{.Image}}\t{{.Status}}" --filter "ancestor=new_edge_access:latest" 2>/dev/null
            echo "Exiting to prevent multiple instances. This is not an error - installation already exists."
            exit 0
        fi
    else
        echo "Container runtime not yet available, container check will be performed after installation"
    fi
}

# Early check for existing containers (before downloading anything)
check_existing_container

# RHEL uses script-based installation (not AMI-based), so no systemd service needed
if is_bwan ; then
    HARDENING_SSH=hardening_ssh_no
elif ! is_rhel ; then
    # Only Ubuntu needs systemd service for AMI-based deployments
    curl -fsSL $S3_PUBLISHER_GENERIC_PATH/npa-publisher.ubuntu.service -o npa-publisher.service
fi

if is_china ; then
    curl -fsSL $S3_PUBLISHER_GENERIC_PATH/npa-publisher-public.pem -o npa-publisher-public.pem
fi

curl -fsSL -o provision_shared.sh $S3_PUBLISHER_GENERIC_PATH/provision_shared.sh
curl -fsSL -o cleanup.sh $S3_PUBLISHER_GENERIC_PATH/cleanup.sh

chmod +x provision_shared.sh
chmod +x cleanup.sh

# Detect platform/OS conditions to pass to provision_shared.sh
IS_RHEL="false"
IS_BWAN="false"
IS_CHINA="false"

[ -f /etc/redhat-release ] && IS_RHEL="true"
[ -d /infroot ] && IS_BWAN="true"
[ -f "$ORIGINAL_HOME/.prc_dp" ] && IS_CHINA="true"

EXIT_CODE=0
./provision_shared.sh "$HARDENING_SSH" "$IS_RHEL" "$IS_BWAN" "$IS_CHINA" || EXIT_CODE=$?
./cleanup.sh

if [ $EXIT_CODE -ne 0 ]; then
    echo "NPA publisher installation failed"
    exit $EXIT_CODE
else
    echo "NPA publisher installation succeeded"
    exit 0
fi
