#!/usr/bin/env python

import json
import os
import time
from datetime import datetime

OPML_START = """<?xml version="1.0" encoding="UTF-8"?>
<!-- OPML generated by SlapOS -->
<opml version="1.1">
	<head>
		<title>SlapOS Monitoring Status Lists</title>
		<dateCreated>%(creation_date)s</dateCreated>
		<dateModified>%(mondification_date)s</dateModified>
	</head>
	<body>
	  <outline text="%(outline_title)s">"""
OPML_END = """	  </outline>
  </body>
</opml>"""

OPML_OUTLINE_FEED = '<outline text="%(title)s" title="%(title)s" type="rss" version="RSS" htmlUrl="%(html_url)s" xmlUrl="%(xml_url)s" />'

def main(config_file, output_file):
  feed_url_list = []
  if os.path.exists(output_file):
    creation_date = datetime.fromtimestamp(os.path.getctime(output_file)).utcnow().strftime("%a, %d %b %Y %H:%M:%S +0000")
    modification_date = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S +0000")
  else:
    creation_date = modification_date = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S +0000")
  with open(config_file, 'r') as fconfig:
    feed_url_list = json.loads(fconfig.read())

  opml_content = OPML_START

	for feed_line in feed_url_list:
		opml_content += OPML_OUTLINE_FEED % {'title': feed_line['title'], 'html_url': feed_line['url'], 'xml_url': feed_line['url']}

	opml_content += OPML_END

  with open(output_file, 'w') as wfile:
    wfile.write(opml_content)

if __name__ == "__main__":
  if len(sys.argv) < 3:
    print("Usage: %s <rss_conf_file> <output_path>" % sys.argv[0])
    sys.exit(2)
	config_file = sys.argv[1]
	output_file = sys.argv[2]
	main(config_file, output_file)