#!/usr/bin/env python3
#
#     erbb
#     Copyright (c) 2020 Raphael DINGE
#
#Tab=3---------------------------------------------------------------------


from __future__ import print_function

import os
import platform
import random
import subprocess
import sys

PATH_THIS = os.path.abspath (os.path.dirname (__file__))
PATH_ROOT = os.path.abspath (os.path.dirname (os.path.dirname (PATH_THIS)))

sys.path.insert (0, os.path.dirname (PATH_THIS))



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

if sys.version_info < (3, 7):
   print ('This script requires python 3.7 or greater.', file=sys.stderr)
   sys.exit (1)

PATH_THIS = os.path.abspath (os.path.dirname (__file__))



#-- find_erbb ----------------------------------------------------------------

def find_erbb ():
   files = os.listdir (os.getcwd ())
   for file in files:
      if file.endswith ('.erbb'):
         return file

   return None



#-- find_erbui ---------------------------------------------------------------

def find_erbui ():
   files = os.listdir (os.getcwd ())
   for file in files:
      if file.endswith ('.erbui'):
         return file

   return None



#-- read_erbb_ast ------------------------------------------------------------

def read_erbb_ast (filepath):
   import erbb

   if filepath is None:
      print ("\033[91mfatal error:\033[0m No erbb file found")
      sys.exit (1)

   try:
      file = open (filepath, 'r', encoding='utf-8')
   except IOError as e:
      print ("\033[91mfatal error:\033[0m Unable to open for read '%s' file: %s" % (args.input, e.strerror))
      sys.exit (1)

   with file:
      try:
         ast = erbb.parse (filepath)
      except erbb.error.Error as error:
         if hasattr (sys.stderr, "isatty") and sys.stderr.isatty ():
            error.color ()
         print (str (error), file=sys.stderr)
         sys.exit (1)

   return ast



#-- read_erbui_ast -----------------------------------------------------------

def read_erbui_ast (filepath):
   import erbui

   if filepath is None:
      print ("\033[91mfatal error:\033[0m No erbui file found")
      sys.exit (1)

   try:
      file = open (filepath, 'r', encoding='utf-8')
   except IOError as e:
      print ("\033[91mfatal error:\033[0m Unable to open for read '%s' file: %s" % (args.input, e.strerror))
      sys.exit (1)

   with file:
      try:
         ast = erbui.parse (filepath)
      except erbui.error.Error as error:
         if hasattr (sys.stderr, "isatty") and sys.stderr.isatty ():
            error.color ()
         print (str (error), file=sys.stderr)
         sys.exit (1)

   return ast



#-- usage --------------------------------------------------------------------

def usage ():
   print ('usage: erbb.py <command> [<args>]\n')
   print ('command:')
   print ('   setup           Install all dependencies')
   print ('   init            Create a new project in current directory')
   print ('   configure       Create the simulator project and hardware make file')
   print ('   build           Build the IDE project or make file')
   print ('   install         Install the firmware on the Daisy hardware')
   print ('   bootloader      Install the QSPI bootloader on the Daisy hardware')
   print ('   max             Cycling\'74 Max commands')
   print ('   faust           Faust commands')
   print ('')
   print ('init [<name>]')
   print ('   name:           Name of project, random name if not specified')
   print ('')
   print ('build [<target> [<configuration>]]')
   print ('   target:')
   print ('      daisy        Daisy firmware (default)')
   print ('      gerber       Front panel PCB files from Kicad file only')
   print ('      hardware     Front panel hardware files')
   print ('      simulator    Simulator plug-in module')
   print ('   configuration:')
   print ('      debug        Debug configuration')
   print ('      release      Release configuration (default)')
   print ('')
   print ('install [<mode> [<configuration>]]')
   print ('   mode:')
   print ('      openocd      Install using OpenOCD if installed (default)')
   print ('      dfu          Install using USB (fallback)')
   print ('   configuration:')
   print ('      debug        Debug configuration')
   print ('      release      Release configuration (default)')
   print ('')
   print ('max init [<name>]')
   print ('   name:           Name of Max project, random name if not specified')
   print ('faust init [<name>]')
   print ('   name:           Name of Faust project, random name if not specified')
   print ('')



#-- setup --------------------------------------------------------------------

def setup ():
   if platform.system () == 'Darwin':
      if 'CI' in os.environ:
         subprocess.check_call ('brew install --cask kicad-minimal.rb', shell=True, cwd=PATH_THIS)
      else:
         kicad_err = subprocess.call ('brew install --cask kicad.rb', shell=True, cwd=PATH_THIS)
         if kicad_err != 0:
            # probably already installed
            print ('Skipping Kicad Install')
      subprocess.check_call ('brew install armmbed/formulae/arm-none-eabi-gcc ninja cairo libffi dfu-util openocd', shell=True)
      subprocess.check_call ('pip3 install -r requirements.txt', shell=True, cwd=PATH_ROOT)
      subprocess.check_call ('mkdir -p ~/Library/Fonts', shell=True)
      subprocess.check_call ('cp include/erb/vcvrack/design/d-din/*.otf ~/Library/Fonts', shell=True, cwd=PATH_ROOT)
      subprocess.check_call ('cp include/erb/vcvrack/design/indie-flower/*.ttf ~/Library/Fonts', shell=True, cwd=PATH_ROOT)

   elif platform.system () == 'Linux':
      subprocess.check_call ('sudo apt-get update', shell=True)
      subprocess.check_call ('sudo apt-get install -y gcc-arm-none-eabi ninja-build libglu1-mesa-dev libcairo2-dev libffi-dev python3-dev kicad libsndfile1 dfu-util openocd', shell=True)
      subprocess.check_call ('pip3 install -r requirements.txt', shell=True, cwd=PATH_ROOT)
      subprocess.check_call ('mkdir -p ~/.local/share/fonts/', shell=True)
      subprocess.check_call ('cp include/erb/vcvrack/design/d-din/*.otf ~/.local/share/fonts', shell=True, cwd=PATH_ROOT)
      subprocess.check_call ('cp include/erb/vcvrack/design/indie-flower/*.ttf ~/.local/share/fonts', shell=True, cwd=PATH_ROOT)

   else:
      print ('Error: Platform %s unsupported' % platform.system ())
      sys.exit (1)



#-- init ---------------------------------------------------------------------

def init ():
   import erbb
   import erbui

   cwd = os.getcwd ()

   name = 'Foo'
   if len (sys.argv) >= 3:
      name = sys.argv [2]
   else:
      name1 = random.choice (('Blu', 'So', 'Ann', 'Hyp', 'Nois', 'X-', 'In', 'Per', 'Tri', 'Tetra', 'Dual', 'Quad', 'Vec'))
      name2 = random.choice (('line', 'nage', 'nor', 'rrr', 'y', 'er', 'tor', 'nator', 'dam', 'dron', 'bre', 'OR'))
      name = name1 + name2

   erbb.init (cwd, name)



#-- configure ----------------------------------------------------------------

def configure ():
   import erbb
   import erbui

   cwd = os.getcwd ()

   ast_erbb = read_erbb_ast (find_erbb ())
   ast_erbui = read_erbui_ast (find_erbui ())

   erbb.generate_gyp (cwd, ast_erbb)
   erbb.configure (cwd, ast_erbb)
   erbb.cleanup (cwd)



#-- build --------------------------------------------------------------------

def build ():
   import erbb
   import erbui

   cwd = os.getcwd ()

   target = 'daisy'
   configuration = 'release'
   if len (sys.argv) >= 3:
      target = sys.argv [2]
   if len (sys.argv) >= 4:
      configuration = sys.argv [3]

   if configuration == 'release':
      configuration = 'Release'
   elif configuration == 'debug':
      configuration = 'Debug'
   else:
      print ("Error: Unknown configuration %s\n" % configuration)
      usage ()
      sys.exit (1)

   if target == 'daisy':
      ast_erbb = read_erbb_ast (find_erbb ())
      module = ast_erbb.modules [0].name
      erbb.build_daisy_target (module, cwd, configuration)
      erbb.objcopy (module, cwd, configuration)

   elif target == 'gerber':
      ast_erbui = read_erbui_ast (find_erbui ())
      path_artifacts = os.path.join (cwd, 'artifacts')
      erbui.generate_front_pcb_gerber (path_artifacts, ast_erbui)

   elif target == 'hardware':
      ast_erbui = read_erbui_ast (find_erbui ())
      path_artifacts = os.path.join (cwd, 'artifacts')
      erbui.generate_front_panel (path_artifacts, ast_erbui)
      erbui.generate_front_pcb (path_artifacts, ast_erbui)

   elif target == 'simulator':
      ast_erbb = read_erbb_ast (find_erbb ())
      module = ast_erbb.modules [0].name
      erbb.build_simulator_make_target (module, cwd, configuration)

   else:
      print ("Error: Unknown target %s\n" % target)
      usage ()
      sys.exit (1)



#-- bootloader ---------------------------------------------------------------

def bootloader ():
   import erbb

   erbb.deploy_bootloader ()



#-- install ------------------------------------------------------------------

def install ():
   import erbb
   import erbui

   cwd = os.getcwd ()

   mode = 'openocd'
   configuration = 'release'
   if len (sys.argv) >= 3:
      mode = sys.argv [2]
   if len (sys.argv) >= 4:
      configuration = sys.argv [3]

   if configuration == 'release':
      configuration = 'Release'
   elif configuration == 'debug':
      configuration = 'Debug'
   else:
      print ("Error: Unknown configuration %s\n" % configuration)
      usage ()
      sys.exit (1)

   if mode == 'openocd':
      force_dfu_util = False
   elif mode == 'dfu':
      force_dfu_util = True
   else:
      print ("Error: Unknown mode %s\n" % mode)
      usage ()
      sys.exit (1)

   ast_erbb = read_erbb_ast (find_erbb ())
   module = ast_erbb.modules [0].name
   section = ast_erbb.modules [0].section.name
   erbb.deploy (module, section, cwd, configuration, force_dfu_util=force_dfu_util)



#-- max ----------------------------------------------------------------------

def max ():
   if len (sys.argv) >= 3:
      command = sys.argv [2]
      if command == 'init':
         max_init ()

   else:
      print ("Error: Missing max command\n")
      usage ()
      sys.exit (1)



#-- max_init -----------------------------------------------------------------

def max_init ():
   import erbb

   cwd = os.getcwd ()

   name = 'Foo'
   if len (sys.argv) >= 4:
      name = sys.argv [3]
   else:
      name1 = random.choice (('Blu', 'So', 'Ann', 'Hyp', 'Nois', 'X-', 'In', 'Per', 'Tri', 'Tetra', 'Dual', 'Quad', 'Vec'))
      name2 = random.choice (('line', 'nage', 'nor', 'rrr', 'y', 'er', 'tor', 'nator', 'dam', 'dron', 'bre', 'OR'))
      name = name1 + name2

   erbb.max_init (cwd, name)



#-- faust --------------------------------------------------------------------

def faust ():
   if len (sys.argv) >= 3:
      command = sys.argv [2]
      if command == 'init':
         faust_init ()

   else:
      print ("Error: Missing faust command\n")
      usage ()
      sys.exit (1)



#-- faust_init ---------------------------------------------------------------

def faust_init ():
   import erbb

   cwd = os.getcwd ()

   name = 'Foo'
   if len (sys.argv) >= 4:
      name = sys.argv [3]
   else:
      name1 = random.choice (('Blu', 'So', 'Ann', 'Hyp', 'Nois', 'X-', 'In', 'Per', 'Tri', 'Tetra', 'Dual', 'Quad', 'Vec'))
      name2 = random.choice (('line', 'nage', 'nor', 'rrr', 'y', 'er', 'tor', 'nator', 'dam', 'dron', 'bre', 'OR'))
      name = name1 + name2

   erbb.faust_init (cwd, name)



#-- main ---------------------------------------------------------------------

def main ():
   cwd = os.getcwd ()
   if len (sys.argv) == 1:
      usage ()

   elif len (sys.argv) >= 2:
      command = sys.argv [1]

      if command == 'setup':
         setup ()

      else:
         import erbb
         import erbui
         try:
            if command == 'init':
               init ()

            elif command == 'configure':
               configure ()

            elif command == 'build':
               build ()

            elif command == 'install':
               install ()

            elif command == 'bootloader':
               bootloader ()

            elif command == 'max':
               max ()

            elif command == 'faust':
               faust ()

            else:
               print ("Error: Unknown command %s\n" % command)
               usage ()
               sys.exit (1)

         except erbb.error.Error as error:
            if hasattr (sys.stderr, "isatty") and sys.stderr.isatty ():
               error.color ()
            print (str (error), file=sys.stderr)
            sys.exit (1)

         except erbui.error.Error as error:
            if hasattr (sys.stderr, "isatty") and sys.stderr.isatty ():
               error.color ()
            print (str (error), file=sys.stderr)
            sys.exit (1)



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

if __name__ == '__main__':
   sys.exit (main ())
