#!/usr/bin/env python
#
# Create project files for all BTstack embedded examples in nRF5_X/examples/btstack

import os
import shutil
import sys
import time
import subprocess

mk_template = '''#
# BTstack example 'EXAMPLE' for n RF5x port
#
# Generated by TOOL
# On DATE

NAME := EXAMPLE

GLOBAL_INCLUDES += .

$(NAME)_SOURCES := ../../../libraries/btstack/example/EXAMPLE.c
$(NAME)_COMPONENTS += btstack/port/wiced
'''

gatt_update_template = '''#!/bin/sh
DIR=`dirname $0`
BTSTACK_ROOT=$DIR/../../../libraries/btstack
echo "Creating EXAMPLE.h from EXAMPLE.gatt"
$BTSTACK_ROOT/tool/compile-gatt.py $BTSTACK_ROOT/example/EXAMPLE.gatt $DIR/EXAMPLE.h
'''

# get script path
script_path = os.path.abspath(os.path.dirname(sys.argv[0]))

# validate nRF5x SDK root by reading version.txt
nrf5x_root = script_path + "/../../../../"

nrf5x_index = ""
try:
    with open(nrf5x_root + '/documentation/index.html', 'r') as fin:
         nrf5x_index = fin.read()  # Read the contents of the file into memory.
except:
    pass
if not "nRF5 SDK Documentation" in nrf5x_index:
    print("Cannot find nRF5 root. Make sure BTstack is checked out in nRF5-SDK-X/components")
    sys.exit(1)

# show nRF5 version
# print("Found %s" % nrf5x_version)

# path to examples
examples_embedded = script_path + "/../../example/"

# path to WICED/apps/btstack
apps_btstack = nrf5x_root + "/examples/btstack/"

print("Creating examples in examples/btstack:")

# iterate over btstack examples
for file in os.listdir(examples_embedded):
    if not file.endswith(".c"):
        continue
    if not file == "gap_le_advertisements.c":
        continue

    example = file[:-2]

    # create folder
    apps_folder = apps_btstack + example + "/"
    if not os.path.exists(apps_folder):
        os.makedirs(apps_folder)

    # just copy current makefiles and config over
    pca10028_folder =  apps_folder+'/pca10028'
    if not os.path.exists(pca10028_folder):
        shutil.copytree(script_path + '/pca10028', pca10028_folder)
    config_folder = apps_folder+'config'
    if not os.path.exists(config_folder):
        shutil.copytree(script_path + '/config', config_folder)
    print("- %s" % example)
    continue

    # will be used later... :)

    # create .mk file
    with open(apps_folder + example + ".mk", "wt") as fout:
        fout.write(mk_template.replace("EXAMPLE", example).replace("TOOL", script_path).replace("DATE",time.strftime("%c")))

    # create update_gatt.sh if .gatt file is present
    gatt_path = examples_embedded + example + ".gatt"
    if os.path.exists(gatt_path):
        update_gatt_script = apps_folder + "update_gatt_db.sh"
        with open(update_gatt_script, "wt") as fout:
            fout.write(gatt_update_template.replace("EXAMPLE", example))        
        os.chmod(update_gatt_script, 0o755)
        subprocess.call(update_gatt_script + "> /dev/null", shell=True)
        print("- %s including compiled GATT DB" % example)
    else:
        print("- %s" % example)

