#!/usr/bin/env python3

import argparse
import os
import subprocess
import logging
import coloredlogs

_LOG = logging.getLogger(__name__)

ROOT = 'examples/all-clusters-app/esp32'
idf_path = os.environ['IDF_PATH']

class IDFExecutor:
  """Runs specified commands via an executor that activates the CHIP build environment."""


  def __init__(self):
    script_path = os.path.dirname(os.path.realpath(__file__))
    self.chip_root = os.path.realpath(os.path.join(script_path, '..', '..'))

    logging.info("CHIP Root directory: %s" % self.chip_root)

    self.run_cmd = os.path.join(self.chip_root, "scripts", "run_in_build_env.sh")
    logging.info("Executing via: %s" % self.run_cmd)

  
  def execute(self, command):
    os.chdir(self.chip_root)
    subprocess.call([self.run_cmd, 'source "%s/export.sh"; cd %s; idf.py %s' % (idf_path, ROOT, command)])


def main():
  """Main task if executed standalone."""
  parser = argparse.ArgumentParser(description='Build all-clusters-app example')
  parser.add_argument(
      '--log-level',
      default=logging.INFO,
      type=lambda x: getattr(logging, x),
      help='Configure the logging level.')
  parser.add_argument(
      '--clear-config',
      default=None,
      choices=['m5stack', 'devkit'],
  )
  args = parser.parse_args()

  # Ensures somewhat pretty logging of what is going on
  logging.basicConfig(
      level=args.log_level,
      format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  coloredlogs.install()

  e = IDFExecutor()

  if args.clear_config:
    logging.info('Building a clear configuration')
    sdkconfig = 'sdkconfig_%s.defaults' % args.clear_config

    curr_sdkconfig = os.path.join(ROOT, 'sdkconfig')
    if os.path.exists(curr_sdkconfig):
      os.remove(curr_sdkconfig)

    e.execute('-D SDKCONFIG_DEFAULTS="{sdkname}" build'.format(
      sdkname=sdkconfig
    ))


  logging.info('Compiling')
  e.execute('build')


if __name__ == '__main__':
  # execute only if run as a script
  main()

@@ -43,16 +43,30 @@
 port os%0A
+import shutil%0A
 import s
@@ -1258,16 +1258,35 @@
 'devkit'
+, 'curr', 'default'
 %5D,%0A  )%0A 
@@ -1560,16 +1560,94 @@
 config:%0A
+    old_default_sdkconfig = None%0A    clear_curr = args.clear_config != 'curr'%0A
     logg
@@ -1689,20 +1689,103 @@
 ation')%0A
+%0A
     
+if args.clear_config == %22m5stack%22 or args.clear_config == %22devkit%22:%0A      desired_
 sdkconfi
@@ -1785,16 +1785,21 @@
 dkconfig
+_name
  = 'sdkc
@@ -1841,100 +1841,511 @@
 fig%0A
-%0A    curr_sdkconfig = os.path.join(ROOT, 'sdkconfig')%0A    if os.path.exists(curr_sdkconfig):
+      logging.info('Using default' + desired_sdkconfig_name)%0A      desired_sdkconfig = os.path.join(ROOT, desired_sdkconfig_name)%0A      default_sdkconfig = os.path.join(ROOT, 'sdkconfig.defaults')%0A      old_default_sdkconfig = os.path.join(ROOT, 'sdkconfig.defaults.old')%0A      shutil.copy(default_sdkconfig, old_default_sdkconfig)%0A      shutil.copy(desired_sdkconfig, default_sdkconfig)%0A%0A    if clear_curr:%0A      logging.info('Clearing current config')%0A      sdkconfig = os.path.join(ROOT, 'sdkconfig')
 %0A   
@@ -2361,13 +2361,8 @@
 ove(
-curr_
 sdkc
@@ -2388,71 +2388,113 @@
 te('
--D SDKCONFIG_DEFAULTS=%22%7Bsdkname%7D%22 build'.format(%0A      sdkname=
+menuconfig')%0A%0A    if old_default_sdkconfig is not None:%0A      shutil.move(old_default_sdkconfig, default_
 sdkc
@@ -2502,16 +2502,9 @@
 nfig
-%0A    ))%0A
+)
 %0A%0A  

Fix clear-config in build-all-clusters-app.py (#8260)