Import('env')
use_ftp = 'y'

# Troubleshooting python modules ================================
# https://docs.platformio.org/en/stable/scripting/examples/extra_python_packages.html
# List installed packages
# env.Execute("$PYTHONEXE -m pip list")

# Install custom packages from the PyPi registry
# env.Execute("$PYTHONEXE -m pip install python-dotenv")

# Install missed package
# try:
#     import dotenv
# except ImportError:
#     env.Execute("$PYTHONEXE -m pip install python-dotenv")
# Troubleshooting python modules END =============================

import os
import shutil
import subprocess
import ftplib
# for passwords
from dotenv import dotenv_values
from dotenv import set_key
from dotenv import get_key

OUTPUT_DIR = "/Volumes/scripts/scripts/001-esp-firmware/esp/01-with_mqtt_discovery/01-Production/0-ESPnow{}".format(os.path.sep)

config = env.GetProjectConfig()
version = config.get("program_customisation", "version")
client = config.get("program_customisation", "client")
client = client.replace('"', '')

def _get_cpp_define_value(env, define):
    define_list = [item[-1] for item in env["CPPDEFINES"] if item[0] == define]

    if define_list:
        return define_list[0]

    return None

def _create_dirs(dirs=["firmware"]):
    # check if output directories exist and create if necessary
    if not os.path.isdir(OUTPUT_DIR):
        os.mkdir(OUTPUT_DIR)

    for d in dirs:
        if not os.path.isdir("{}{}".format(OUTPUT_DIR, d)):
            os.mkdir("{}{}".format(OUTPUT_DIR, d))

def bin_rename_copy(source, target, env):
    print()
    print("============== bin_rename_copy =================================")
    _create_dirs()
    variant = env["PIOENV"]
    bin_file = "{}firmware{}{}.bin".format(OUTPUT_DIR, os.path.sep, variant)
    fw_file = "{}.bin".format(variant)
    ver_file = "{}.bin.version".format(variant)
    print("firmware file:",fw_file)
    print("version file:",ver_file)
    print("version:",version) 
    print("client:",client)
    shutil.copy(str(target[0]), bin_file)

# version file
    version_file = "{}firmware{}{}.bin.version".format(OUTPUT_DIR, os.path.sep, variant)
    config = env.GetProjectConfig()
    ver = config.get("program_customisation", "version")
    ver = ver.replace('"', '')
    print("version compiled (inside version file):",ver)
    file = open(version_file,"w")
    file.write(ver)
    file.close()



    # ftp transfer
    # get credentials:
    if (use_ftp != 'y'):
        print("============== FTP  ===========================================")
        print("NOT sending firmware to ftp server")
        print("============== FTP  END =======================================")
        print()
    else:
        print()
        print("============== FTP DETAILS     =================================")
        print("Uploading firmware to ftp server...")
        password_file=(os.getcwd()) + "/src/passwords_ftp.h"
        # print("password_file:     ",password_file)
        config = dotenv_values(password_file)
        FTP_HOST=config['FTP_HOST']
        # print("host=",FTP_HOST)
        FTP_USER=config['FTP_USER']
        # print("user=",FTP_USER)
        FTP_PASSWORD=config['FTP_PASSWORD']
        # print("password=",FTP_PASSWORD)
        FTP_DEST_DIR=config['FTP_DEST_DIR'] + "/" + client + "/" + config['FTP_DEST_SUBDIR']
        print("destination folder2: ftp://",FTP_HOST,"/",FTP_DEST_DIR,sep='')  
        print()
        print("============== TRANSFER FIRMWARE FILE ==========================")
        ftp = ftplib.FTP_TLS(FTP_HOST)
        ftp.login(FTP_USER, FTP_PASSWORD)
        ftp.prot_p()
        # print("landing dir: ",ftp.pwd())
        # print("content:")
        # ftp.dir()
        ftp.cwd(FTP_DEST_DIR)
        # print("dest dir: ",ftp.pwd())
        # print("content:")
        # ftp.dir()

        # bin_file
        print("Firmware file to store:     ",bin_file)
        file = open(bin_file,"rb")
        command = "STOR " + fw_file
        ftp.storbinary(command, file)
        file.close()

        print()
        print("============== TRANSFER VERSION FILE ===========================")
        # version_file
        print("Version file to store:      ",version_file)
        file = open(version_file,"rb")
        command = "STOR " + ver_file
        ftp.storbinary(command, file)
        file.close()

        print()
        print("============== FTP RESULTS: ====================================")
        print("destination folder: ",ftp.pwd())
        print("content after transfer:")
        ftp.dir()
        ftp.close()
        print("============== FTP  END ========================================")
        print()


env.AddPostAction("$BUILD_DIR/${PROGNAME}.bin", [bin_rename_copy])
