// Copyright 2024 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package build_flags

import (
	"android/soong/android"

	"github.com/google/blueprint"
)

const (
	outJsonFileName = "build_flags.json"
)

func init() {
	registerBuildFlagsModuleType(android.InitRegistrationContext)
}

func registerBuildFlagsModuleType(ctx android.RegistrationContext) {
	ctx.RegisterModuleType("build_flags_json", buildFlagsFactory)
}

type buildFlagsProperties struct {
	// List of allReleaseConfig files the module depends on.
	Deps []string `android:"path"`
}

type buildFlags struct {
	android.ModuleBase
	properties buildFlagsProperties

	outputPath android.Path
}

func buildFlagsFactory() android.Module {
	module := &buildFlags{}
	module.AddProperties(&module.properties)
	android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
	return module
}

func (m *buildFlags) UseGenericConfig() bool {
	return false
}

func (m *buildFlags) GenerateAndroidBuildActions(ctx android.ModuleContext) {
	// Read the build_flags_<partition>.json file generated by the
	// 'release-config' command.
	var srcFiles []android.Path

	partition := m.PartitionTag(ctx.DeviceConfig())
	ctx.VisitDirectDepsProxyWithTag(buildFlagsTag, func(module android.ModuleProxy) {
		if dep, ok := android.OtherModuleProvider(ctx, module, ReleaseConfigProviderKey); ok {
			switch partition {
			case "product":
				srcFiles = append(srcFiles, dep.BuildFlagsProductJson)
			case "system":
				srcFiles = append(srcFiles, dep.BuildFlagsSystemJson)
			case "system_ext":
				srcFiles = append(srcFiles, dep.BuildFlagsSystemExtJson)
			case "vendor":
				srcFiles = append(srcFiles, dep.BuildFlagsVendorJson)
			default:
				ctx.ModuleErrorf("Unknown partition '%s'", partition)
			}
		} else {
			ctx.OtherModuleErrorf(module, "No ReleaseConfigProvider data")
		}
	})
	if len(srcFiles) == 0 {
		ctx.ModuleErrorf("Did not find source file for partition %s", partition)
		return
	} else if len(srcFiles) > 1 {
		ctx.ModuleErrorf("Cannot specify more than one dependency for partition %s, found: %v", partition, srcFiles)
		return
	}
	srcPath := srcFiles[0]
	outputPath := android.PathForModuleOut(ctx, outJsonFileName)

	// The 'release-config' command is called for every build, and generates the
	// build_flags_<target_product>-<partition>.json file.
	// Update the output file only if the source file is changed.
	ctx.Build(pctx, android.BuildParams{
		Rule:   android.CpIfChanged,
		Input:  srcPath,
		Output: outputPath,
	})

	installPath := android.PathForModuleInstall(ctx, "etc")
	ctx.InstallFile(installPath, outJsonFileName, outputPath)
	m.outputPath = outputPath
}

func (m *buildFlags) AndroidMkEntries() []android.AndroidMkEntries {
	return []android.AndroidMkEntries{android.AndroidMkEntries{
		Class:      "ETC",
		OutputFile: android.OptionalPathForPath(m.outputPath),
	}}
}

type buildFlagsDependencyTag struct {
	blueprint.BaseDependencyTag
}

var buildFlagsTag = buildFlagsDependencyTag{}

func (m *buildFlags) DepsMutator(ctx android.BottomUpMutatorContext) {
	for _, dep := range m.properties.Deps {
		ctx.AddDependency(m, buildFlagsTag, dep)
	}
}
