#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright The IETF Trust 2018, All Rights Reserved

"""
NAME
	%(program)s - Call out to an uglifying service to minify javascript

SYNOPSIS
	%(program)s [OPTIONS] SENTMAILDIR

DESCRIPTION
	Call out to the uglifying service at javascript-minifier.com to minify
        the indicated javascript.

%(options)s

AUTHOR
	Written by Henrik Levkowetz, <henrik@levkowetz.com> based on code found
        at https://javascript-minifier.com/python.

COPYRIGHT
	Copyright 2011 Henrik Levkowetz

	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. There is NO WARRANTY; not even the
	implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
	PURPOSE. See the GNU General Public License for more details.

"""

import sys
import os.path
import getopt
import re

version = "0.10"
program = os.path.basename(sys.argv[0])
progdir = os.path.dirname(sys.argv[0])

# ----------------------------------------------------------------------
# Parse options

options = ""
for line in re.findall("\n +(if|elif) +opt in \[(.+)\]:\s+#(.+)\n", open(sys.argv[0]).read()):
    if not options:
        options += "OPTIONS\n"
    options += "        %-16s %s\n" % (line[1].replace('"', ''), line[2])
options = options.strip()

# with ' < 1:' on the next line, this is a no-op:
if len(sys.argv) <= 1:
    print(__doc__ % locals())
    sys.exit(1)

try:
    opts, files = getopt.gnu_getopt(sys.argv[1:], "hvV", ["help", "version","verbose",])
except Exception as e:
    print("%s: %s" % (program, e))
    sys.exit(1)

# ----------------------------------------------------------------------
# Handle options

# set default values, if any
opt_verbose = False
opt_days = 8                            # Report on monday for previous week
opt_email_path = ""

# handle individual options
for opt, value in opts:
    if   opt in ["-h", "--help"]: # Output this help, then exit
        print(__doc__ % locals())
        sys.exit(1)
    elif opt in ["-v", "--version"]: # Output version information, then exit
        print(program, version)
        sys.exit(0)
    elif opt in ["-V", "--verbose"]: # Output version information, then exit
        opt_verbose = True

# ----------------------------------------------------------------------
def die(s):
    sys.stderr.write("%s: Error: %s\n" % (program, s))
    sys.exit(2)

# ----------------------------------------------------------------------
def warn(s):
    sys.stderr.write("%s: Warning: %s\n" % (program, s))

# ----------------------------------------------------------------------
def say(s):
    sys.stdout.write("%s\n" % (s))

# ----------------------------------------------------------------------
def note(s):
    if opt_verbose:
        sys.stderr.write("%s\n" % (s))

# ----------------------------------------------------------------------
# The program itself    

import sys
import requests

url = 'https://javascript-minifier.com/raw'
if not files:
    sys.stdout.write("Missing input argument, nothing to do\n")
    sys.exit(1)

for file in files:
    # Grab the file contents
    with open(file, 'r') as f:
        text = f.read()

    # Pack it, ship it    
    payload = {'input': text}
    sys.stderr.write("Requesting minified version of %s ...\n" % file)
    r = requests.post(url, payload)
    if r.status_code == 200:
        # Write out minified version
        base, ext = os.path.splitext(file)
        ofn = base + '.min' + ext
        with open(ofn, 'w') as f:
            f.write(r.text)
            sys.stderr.write("Wrote %s\n" % ofn)
    else:
        sys.stderr.write("Error response from %s, got status code %s (%s)\n" % (url, r.status_code, r.reason))
