android: implement WriteLKGB endpoint

BUG=b:210065671
TEST=./api/compile_build_api_proto && ./run_tests
TEST=./api/contrib/gen_call_scripts && \
       ./api/contrib/call_scripts/android__write_lkgb

Cq-Depend: chromium:3328476
Change-Id: I1a648817793a46cad94faffdbbfb4f7c60031e07
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/chromite/+/3327839
Reviewed-by: Jaques Clapauch <jaquesc@google.com>
Tested-by: Shao-Chuan Lee <shaochuan@chromium.org>
Commit-Queue: Shao-Chuan Lee <shaochuan@chromium.org>
diff --git a/api/controller/android.py b/api/controller/android.py
index 0eb76e9..0b21ecd 100644
--- a/api/controller/android.py
+++ b/api/controller/android.py
@@ -4,6 +4,7 @@
 
 """Android operations."""
 
+import logging
 import os
 from typing import TYPE_CHECKING
 
@@ -121,3 +122,37 @@
     _config: The call config.
   """
   osutils.SafeUnlink(ANDROIDPIN_MASK_PATH)
+
+
+def _WriteLKGBResponse(_input_proto, output_proto, _config):
+  """Fake WriteLKGB response."""
+  output_proto.modified_files.append('fake_file')
+
+
+@faux.success(_WriteLKGBResponse)
+@faux.empty_error
+@validate.require('android_package', 'android_version')
+@validate.validation_complete
+def WriteLKGB(input_proto, output_proto, _config):
+  android_package = input_proto.android_package
+  android_version = input_proto.android_version
+  android_package_dir = android.GetAndroidPackageDir(android_package)
+
+  # Attempt to read current LKGB, if available.
+  current_lkgb = None
+  try:
+    current_lkgb = android.ReadLKGB(android_package_dir)
+  except android.MissingLKGBError:
+    logging.info('LKGB file is missing, creating a new one.')
+  except android.InvalidLKGBError:
+    logging.warning('Current LKGB file is invalid, overwriting.')
+
+  # Do nothing if LKGB is already set to the requested version.
+  if current_lkgb == android_version:
+    logging.warning('LKGB of %s is already %s, doing nothing.',
+                    android_package, android_version)
+    return
+
+  # Actually update LKGB.
+  lkgb = android.WriteLKGB(android_package_dir, android_version)
+  output_proto.modified_files.append(lkgb)