// Copyright (c) 2026 Tigera, 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 archives

import (
	"archive/tar"
	"compress/gzip"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"

	"github.com/projectcalico/calico/release/internal/command"
	"github.com/projectcalico/calico/release/internal/env"
	"github.com/projectcalico/calico/release/internal/fsutil"
	"github.com/projectcalico/calico/release/internal/steps"
)

func beforeBuild(a Archive) (cleanupFn func() error, err error) {
	dir := a.stagingDir()
	cleanupFn = func() error {
		return os.RemoveAll(dir)
	}
	if err := cleanupFn(); err != nil {
		return nil, fmt.Errorf("clearing staging dir %s: %w", dir, err)
	}
	if err := os.Remove(Path(a)); err != nil && !os.IsNotExist(err) {
		return nil, fmt.Errorf("clearing old archive %s: %w", Path(a), err)
	}
	return cleanupFn, nil
}

func Build(a Archive, opts ...BuildOption) error {
	s, err := newSettings(buildStep, a, validateSources, opts)
	if err != nil {
		return err
	}
	cleanup, err := beforeBuild(s.Archive)
	if err != nil {
		return err
	}
	defer func() {
		if err := cleanup(); err != nil {
			s.Logger().WithError(err).Warn("Cleanup failed")
		}
	}()

	s.Logger().WithField("sources", len(s.Sources)).Info("Building release archive")
	if err := s.write(s.stagingDir()); err != nil {
		if rmErr := os.Remove(Path(s.Archive)); rmErr != nil && !os.IsNotExist(rmErr) {
			s.Logger().WithError(rmErr).Warn("Failed to remove the partial archive")
		}
		return err
	}
	s.Logger().WithField("path", Path(s.Archive)).Info("Built release archive")
	return nil
}

// Each source is staged, archived and deleted before the next, so the disk
// holds the archive and one source at a time rather than every image tar.
func (s settings) write(staging string) error {
	if err := os.MkdirAll(s.OutputDir, fsutil.DirPerms); err != nil {
		return s.Errorf("creating %s: %w", s.OutputDir, err)
	}
	f, err := os.Create(Path(s.Archive))
	if err != nil {
		return s.Errorf("creating %s: %w", Path(s.Archive), err)
	}
	defer func() { _ = f.Close() }()
	zw := gzip.NewWriter(f)
	tw := tar.NewWriter(zw)

	root := filepath.Base(staging)
	written := map[string]bool{}
	for _, c := range s.Sources {
		if err := os.MkdirAll(staging, fsutil.DirPerms); err != nil {
			return s.Errorf("creating %s: %w", staging, err)
		}
		if err := c.Contribute(staging); err != nil {
			return s.Errorf("staging %s: %w", c.Name(), err)
		}
		if err := filepath.WalkDir(staging, func(path string, d fs.DirEntry, err error) error {
			if err != nil {
				return err
			}
			rel, err := filepath.Rel(staging, path)
			if err != nil {
				return err
			}
			name := filepath.ToSlash(filepath.Join(root, rel))
			if d.IsDir() {
				// Sources share directories such as bin/, and a tar lists each once.
				if written[name] {
					return nil
				}
				written[name] = true
			} else if !d.Type().IsRegular() {
				return fmt.Errorf("%s is not a regular file", path)
			}
			info, err := d.Info()
			if err != nil {
				return err
			}
			hdr, err := tar.FileInfoHeader(info, "")
			if err != nil {
				return err
			}
			hdr.Name = name
			if d.IsDir() {
				hdr.Name += "/"
			}
			if err := tw.WriteHeader(hdr); err != nil {
				return err
			}
			if d.IsDir() {
				return nil
			}
			src, err := os.Open(path)
			if err != nil {
				return err
			}
			defer func() { _ = src.Close() }()
			_, err = io.Copy(tw, src)
			return err
		}); err != nil {
			return s.Errorf("archiving %s: %w", c.Name(), err)
		}
		if err := os.RemoveAll(staging); err != nil {
			return s.Errorf("clearing staged %s: %w", c.Name(), err)
		}
		s.Logger().WithField("source", c.Name()).Info("Archived")
	}

	if err := tw.Close(); err != nil {
		return s.Errorf("finishing %s: %w", Path(s.Archive), err)
	}
	if err := zw.Close(); err != nil {
		return s.Errorf("compressing %s: %w", Path(s.Archive), err)
	}
	if err := f.Close(); err != nil {
		return s.Errorf("closing %s: %w", Path(s.Archive), err)
	}
	return nil
}

// BuildWindows builds the Windows archive and its install script into the
// output directory, beside the release tarball rather than inside it.
func BuildWindows(a Archive, opts ...WindowsOption) error {
	s, err := newSettings(windowsStep, a, validateWindows, opts)
	if err != nil {
		return err
	}

	vars := []string{env.Var(env.Version, s.Version)}
	dir := filepath.Join(s.RepoRoot, windowsComponent)
	// The install script is a file target with no prerequisites, so make skips
	// it when one is already there and the stale version's script survives.
	if err := os.Remove(filepath.Join(dir, windowsScriptTarget)); err != nil && !os.IsNotExist(err) {
		return s.Errorf("clearing stale %s: %w", windowsScriptTarget, err)
	}
	for _, target := range []string{windowsArchiveTarget, windowsScriptTarget} {
		if _, err := command.Make(s.Runner(), dir).Run([]string{target}, command.WithEnv(vars...), command.WithLogFile(s.LogPath(target))); err != nil {
			return s.Errorf("building %s: %w", target, err)
		}
	}

	collect := map[string]string{
		WindowsFileName(s.Version): WindowsDir(s.OutputDir),
		windowsScript:              WindowsScriptDir(s.OutputDir),
	}
	for name, dst := range collect {
		if err := os.MkdirAll(dst, fsutil.DirPerms); err != nil {
			return s.Errorf("creating %s: %w", dst, err)
		}
		if err := fsutil.LinkOrCopyFile(filepath.Join(dir, windowsDistDir, name), filepath.Join(dst, name)); err != nil {
			return s.Errorf("collecting %s: %w", name, err)
		}
	}
	s.Logger().WithField("dir", WindowsDir(s.OutputDir)).Info("Built Windows archive")
	return nil
}

func newSettings[O any](step string, a Archive, validate func(a Archive) error, opts []O) (settings, error) {
	s := settings{Archive: a}
	s.Apply([]steps.Option{steps.WithName(step)})
	if err := validate(a); err != nil {
		return s, s.Errorf("%w", err)
	}
	for _, opt := range opts {
		if err := applyTo(opt, &s); err != nil {
			return s, s.Errorf("%w", err)
		}
	}
	return s, nil
}

func applyTo(opt any, s *settings) error {
	switch o := opt.(type) {
	case BuildOption:
		return o.applyBuild(s)
	case WindowsOption:
		return o.applyWindows(s)
	default:
		return fmt.Errorf("unknown option type %T", opt)
	}
}
