#!/bin/bash
################################################################################
# Copyright (C) 2019-2024 NI SP GmbH
# All Rights Reserved
#
# info@ni-sp.com / www.ni-sp.com
#
# We provide the information on an as is basis.
# We provide no warranties, express or implied, related to the
# accuracy, completeness, timeliness, useability, and/or merchantability
# of the data and are not liable for any loss, damage, claim, liability,
# expense, or penalty, or for any direct, indirect, special, secondary,
# incidental, consequential, or exemplary damages or lost profit
# deriving from the use or misuse of this information.
################################################################################
# Version v1.1
#

# wget https://www.ni-sp.com/wp-content/uploads/2019/10/DCVSM/DCVSM-conf-server.sh

# Check if Python3 is installed
if ! command -v python3 &> /dev/null; then
    echo "Python3 is not installed. Please install Python3..."
    # sudo apt-get update
    # sudo apt-get install -y python3
    exit
else
    echo "Python3 is already installed."
fi

# Check if pip3 is installed
if ! command -v pip3 &> /dev/null; then
    echo "pip3 is not installed. Please install pip3..."
    # sudo apt-get update
    # sudo apt-get install -y python3-pip
    exit
else
    echo "pip3 is already installed, e.g. package python3-pip"
fi

# Install Flask using pip
sudo pip3 install flask

# Execute the Python script piped into Python
sudo python3 <<EOF
from flask import Flask, send_file, jsonify
import os
import subprocess

app = Flask(__name__)

# Define paths to files and ensure they are accessible with sudo
PEM_FILE = "/var/lib/dcvsmbroker/security/dcvsmbroker_ca.pem"
PROPERTIES_FILE = "/etc/dcv-session-manager-broker/session-manager-broker.properties"

def get_ec2_metadata(metadata_path):
    url = f"http://169.254.169.254/latest/meta-data/{metadata_path}"
    try:
        result = subprocess.run(['curl', '-s', url], capture_output=True, text=True, check=True)
        return result.stdout.strip()
    except subprocess.CalledProcessError:
        print(f"Error retrieving {metadata_path} from EC2 metadata")
        return None


# Helper function to read properties file
def get_property(filename, property_name):
    try:
        with open(filename, 'r') as f:
            for line in f:
                if line.startswith(property_name):
                    return line.split('=')[1].strip()
        return None  # Property not found
    except FileNotFoundError:
        return None
    except Exception as e:
        print(f"Error reading properties file: {e}")
        return None


@app.route('/download_pem')
def download_pem():
    """Downloads the dcvsmbroker_ca.pem file."""
    try:
        # Use send_file for efficient file serving
        return send_file(PEM_FILE, as_attachment=True, download_name="dcvsmbroker_ca.pem")
    except FileNotFoundError:
        return "PEM file not found", 404
    except Exception as e:
        print(f"Error sending PEM file: {e}")
        return "Error sending PEM file", 500


@app.route('/broker_info')
def broker_info():
    """Returns the broker port and hostname."""
    try:
        port = get_property(PROPERTIES_FILE, "agent-to-broker-connector-https-port")
        if port is None:
            return "agent-to-broker-connector-https-port not found in properties file", 500
        # Get the EC2 public DNS
        hostname = get_ec2_metadata('public-hostname')
        if not hostname:
            hostname = os.uname()[1] # Gets the system's hostname
        return jsonify({"port": port, "hostname": hostname})

    except Exception as e:
        print(f"Error retrieving broker info: {e}")
        return "Error retrieving broker info", 500

if __name__ == '__main__':
    #   app.run(debug=True, host='0.0.0.0') # Listen on all interfaces for development
    app.run(debug=False, host='0.0.0.0') # Listen on all interfaces for development


EOF

echo "DCV SM Config Server finished"

