#!/bin/bash

# Improved deployObserv-arm64.sh with better error handling and portability

set -e  # Exit on any error

AVSONO_NNM_INSTALLER="avsono-nnm-1.2.7-docker-x86_64-installer.run"
LICENSE_FILE="diversified_nnm_license_30062025.lic"

# Default values
USER_EMAIL="default@example.com"
PASSWORD="password"
USERNAME="defaultuser"
FIRST_NAME="Default"
LAST_NAME="User"

# Function to generate password hash (portable across Linux/macOS)
generate_password_hash() {
    if command -v md5sum >/dev/null 2>&1; then
        echo -n "$1" | md5sum | awk '{print $1}'
    elif command -v md5 >/dev/null 2>&1; then
        echo -n "$1" | md5
    else
        echo "Error: Neither md5sum nor md5 command found" >&2
        exit 1
    fi
}

# Check if any arguments are provided
if [ $# -eq 0 ]; then
    echo "Enter the required parameters to login to the Avsono NNM Web Configuration page."
    echo "Usage: $0 --email <email> --password <password> --username <username> --firstname <firstname> --lastname <lastname>"
    exit 1
fi

# Read command line arguments
while [[ $# -gt 0 ]]; do
    case "$1" in
        --email)
            USER_EMAIL="$2"
            shift 2
            ;;
        --password)
            PASSWORD="$2"
            shift 2
            ;;
        --username)
            USERNAME="$2"
            shift 2
            ;;
        --firstname)
            FIRST_NAME="$2"
            shift 2
            ;;
        --lastname)
            LAST_NAME="$2"
            shift 2
            ;;
        *)
            echo "Unknown parameter: $1"
            exit 1
            ;;
    esac
done

# Generate password hash
echo "Generating password hash..."
PASSWORD_HASH=$(generate_password_hash "$PASSWORD")

# Download installer with error checking
echo "Downloading $AVSONO_NNM_INSTALLER ..."
if ! curl -O "https://tfcodedeploy.s3.us-east-2.amazonaws.com/$AVSONO_NNM_INSTALLER"; then
    echo "Error: Failed to download installer" >&2
    exit 1
fi

echo "Downloading license file $LICENSE_FILE ..."
curl -O "https://tfcodedeploy.s3.us-east-2.amazonaws.com/$LICENSE_FILE"

# Verify installer was downloaded
if [ ! -f "$AVSONO_NNM_INSTALLER" ]; then
    echo "Error: Installer file not found after download" >&2
    exit 1
fi

# Make Avsono NNM installer executable
chmod +x "$AVSONO_NNM_INSTALLER"


# Create configuration file
echo "Creating configuration files..."
cat <<EOF > config.sh
# Required installation config options for the Avsono NNM
# =======================================================

# Required installation config options for the Gateway
# ====================================================
GATEWAY_NAME="Avsono-Nnm-Gateway-1"
GATEWAY_PORT="8000"

JOB_SERVER_API_TOKEN="550e8400-e29b-41d4-a716-446655440000"
JOB_SERVER_URL="http://localhost:8001"

METRICS_PUSH_SERVER_URL="http://localhost:9091"
METRICS_PUSH_SERVER_JOBNAME="NDI_CLIENTS"

LICENSE_FILE="$LICENSE_FILE"
LICENSE_KEY="key/eyJhY2NvdW50Ijp7ImlkIjoiNzJkM2ZiNDktNmM4MC00Njk0LTkxNzUtNzNhMmUxZWU0YWRkIn0sInByb2R1Y3QiOnsiaWQiOiJiYTdlODAyNS02ZDczLTQzN2YtYmI4ZC05OWZiMDhiMThhZDEifSwicG9saWN5Ijp7ImlkIjoiNDkyNDAwNjItOWU1Ny00OTRlLTk5ODItNmM0NmJhYTI1MGEwIiwiZHVyYXRpb24iOjMxNTM2MDAwfSwidXNlciI6bnVsbCwibGljZW5zZSI6eyJpZCI6Ijg4NmU2NzgzLTExNzAtNDBmYi05NWZkLTM3MzJkZmFmZWFhZCIsImNyZWF0ZWQiOiIyMDI1LTA0LTMwVDIwOjQyOjU3LjYwNFoiLCJleHBpcnkiOiIyMDI1LTA1LTMwVDAwOjAwOjAwLjAwMFoifX0=.3HFKBttCq6aWy4QQyWqJwTTcAYpYy-4kQNil8z-ajQFne5-iKY2nh5W5P3c244Uo6SErOLb5XNoX0QdqM9uABA=="


# Installation config options for the WebApp using https
# ======================================================
WEBAPP_ENABLE_HTTPS="false"
WEBAPP_PORT=8080
BACKEND_URL="http://localhost:8001"

# Installation config options for the Jobs Manager
# =========================================================
JMGR_SERVER_PORT=8001
JMGR_USERS_FILE="jmgr_users.toml"

# Log file configuration options to handle log rotation and retention policies
GATEWAY_LOG_MAX_SIZE="10m"
GATEWAY_LOG_MAX_FILE="3"
WEBAPP_LOG_MAX_SIZE="10m"
WEBAPP_LOG_MAX_FILE="3"
JMGR_LOG_MAX_SIZE="10m"
JMGR_LOG_MAX_FILE="3"
EOF

# Create jmgr_users.toml in the current directory so it can be copied after installation
cat <<EOF > jmgr_users.toml
[[user]]
email = "$USER_EMAIL"
password = "$PASSWORD_HASH" # hashed password from CLI
username = "$USERNAME"
first_name = "$FIRST_NAME"
last_name = "$LAST_NAME"
role = "admin"

[[user]]
email = "user@avsono.com"
password = "f9e893abe85585529902eb6cc622b3eb298057c9010ce1cf3af62a99efb7d17c" # user@123
username = "user"
first_name = "Avsono"
last_name = "User"

[[user]]
email = "other@avsono.com"
password = "962be226e33facb6600a330ed3e0a40f063b627ac7de6505dc812b1c3093d79a" # other@123
username = "other"
first_name = "Other"
last_name = "Avsono User"
EOF

# Run installer with error checking
echo "Running Avsono NNM installer..."
if ! ./"$AVSONO_NNM_INSTALLER" --accept --nox11 -- --install-all --options config.sh; then
    echo "Error: Avsono NNM installation failed" >&2
    exit 1
fi

sudo cp ./$LICENSE_FILE /opt/avsono/docker/conf/

echo "Avsono NNM Installation completed successfully."
