#!/usr/bin/python3.6 -s
# GPL. (C) 2025 Paolo Patruno.

# This program is free software; you can redistribute it and/or modify 
# it under the terms of the GNU General Public License as published by 
# the Free Software Foundation; either version 2 of the License, or 
# (at your option) any later version. 
# 
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
# GNU General Public License for more details. 
# 
# You should have received a copy of the GNU General Public License 
# along with this program; if not, write to the Free Software 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
# 

import pika
import ssl
import logging
import rmap.settings

import optparse
from rmap import  __version__

logging.basicConfig(level=logging.WARNING)

p = optparse.OptionParser(usage="usage: %prog [options] filename",version="%prog "+__version__)
p.add_option('--username',    default=rmap.settings.amqpuser,        help="amqp username (default = %default)")
p.add_option('--password',    default=rmap.settings.amqppassword,    help="amqp password (default = as in config file)")
p.add_option('--host',        default=rmap.settings.amqphost,        help="broker hostname (default = %default)")
p.add_option('--exchange',    default="rmap.mqtt.bufr.report_fixed", help="broker exchange name (default = %default)")
p.add_option('--routing_key', default="amqp_producer",               help="broker routing key (default = %default)")
p.add_option("--amqps",       default=False, action="store_true",    help="use secure AMQP (default = %default)")
(options, args) = p.parse_args()
if len(args) != 1:
    p.print_help()
    raise optparse.OptionValueError("incorrect number of arguments")

filename=args[0]

# Legge un file.
with open(filename,"rb") as file :
    body = file.read()

#context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context = ssl.create_default_context()
context.verify_mode = ssl.CERT_REQUIRED

credentials=pika.PlainCredentials(options.username, options.password)
properties=pika.BasicProperties(
    user_id= options.username,
    delivery_mode = 2, # persistent
)

if (options.amqps):
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        ssl_options=pika.SSLOptions(context), port=5671,
        host=options.host,credentials=credentials))
else:
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        host=options.host,credentials=credentials))

channel = connection.channel()

#channel.queue_declare(queue=queue)

channel.basic_publish(exchange=options.exchange,
                      routing_key=options.routing_key,
                      body=body,
                      properties=properties)

print(" [OK] Sent")
connection.close()
