#!/usr/bin/env python

import os, sys, time
import bpy
from math import pi
import glob
import shutil
from mathutils import Vector, Matrix
from math import radians, pi

argv = sys.argv
argv = argv[argv.index("--") + 1:]

incpath = os.path.dirname(__file__)

sys.path.insert(0, incpath)
sys.path.insert(1, incpath + "/blender2ogre")

gltf_file = argv[0]
target_name = argv[1]

bpy.ops.object.mode_set(mode='OBJECT')

bpy.ops.object.select_all(action='DESELECT')

print("Target: " + target_name)
for o in bpy.data.objects:
    print(o.name)

obj = bpy.data.objects.get(target_name)
obj.select_set(True)

armature = obj.parent if (obj.parent and obj.parent.type == 'ARMATURE') else None
if not armature:
    for mod in obj.modifiers:
        if mod.type == 'ARMATURE' and mod.object:
            armature = mod.object
            break
if armature:
    armature.select_set(True)
    bpy.context.view_layer.objects.active = armature
else:
    raise Exception("bad armature")
print("Exporting to " + gltf_file)
basepath = incpath

bpy.ops.export_scene.gltf(filepath=gltf_file,
        use_selection=True,
        check_existing=False,
        export_format='GLB',
        export_texture_dir='textures', export_texcoords=True,
        export_animation_mode='NLA_TRACKS',
        export_normals=True,
        export_tangents=True,
        export_materials='EXPORT',
        export_colors=True,
        use_mesh_edges=False,
        use_mesh_vertices=False,
        export_cameras=False,
        use_visible=False,
        use_renderable=False,
        export_yup=True,
        export_apply=True,
        export_animations=True,
        export_force_sampling=True,
        export_def_bones=False,
        export_current_frame=False,
        export_morph=True,
        export_morph_animation=False,
        export_morph_normal=True,
        export_morph_tangent=True,
        export_lights=False,
        export_skins=True)

bpy.ops.wm.read_homefile(use_empty=True)
time.sleep(2)
bpy.ops.wm.quit_blender()

