#!/usr/bin/env python3

import sys
import os
import stat
import subprocess
import zipfile
import getopt

# ---------------------------------------------------------------------

# parse the command-line options
output_fname = None
opts,args = getopt.getopt( sys.argv[1:], "o:", ["output="] )
for opt,val in opts:
    if opt in ["-o","--output"]:
        output_fname = val.strip()
    else:
        raise RuntimeError( "Unknown argument: {}".format( opt ) )
if not output_fname:
    raise RuntimeError( "No output file was specified." )
if os.path.splitext( output_fname )[1] != ".zip":
    raise RuntimeError( "Only ZIP files are supported." )
if os.path.isfile( output_fname ):
    raise RuntimeError( "Output file exists." )

# initialize
os.chdir( os.path.split( __file__ )[0] )

# compile the program
print( "=== COMPILING ===" )
print()
proc = subprocess.run( [ "make", "clean", "all" ] )
print()
if proc.returncode != 0:
    sys.exit( 1 )

# create the release
print( "=== CREATING RELEASE ===" )
print()
with zipfile.ZipFile( output_fname, "w" ) as zip_file:
    # add the binaries
    os.chdir( "out" )
    for fname in os.listdir( "." ):
        if os.path.splitext( fname )[1] == ".exe":
            flags = os.stat( fname ).st_mode
            os.chmod( fname, flags | stat.S_IEXEC )
        zip_file.write( fname )
    os.chdir( ".." )
    # add the license
    zip_file.write( "LICENSE.txt" )
    # add the data/ and resources/ directories
    for dname in ("data","resources"):
        for root, dnames, fnames in os.walk( dname ):
            for fname in fnames:
                zip_file.write( os.path.join( root, fname ) )

# dump the generated release file
os.system( "ls -lh {}".format( output_fname ) )
print()
os.system( "unzip -l {}".format( output_fname ) )
