package cli

import (
	"context"

	"github.com/pkg/errors"

	"github.com/kopia/kopia/internal/acl"
	"github.com/kopia/kopia/internal/auth"
	"github.com/kopia/kopia/repo"
)

var (
	aclEnableCommand = aclCommands.Command("enable", "Enable ACLs and install default entries")
	aclEnableReset   = aclCommands.Flag("reset", "Reset all ACLs to default").Bool()
)

func runACLEnable(ctx context.Context, rep repo.RepositoryWriter) error {
	entries, err := acl.LoadEntries(ctx, rep, nil)
	if err != nil {
		return errors.Wrap(err, "error loading ACL entries")
	}

	if len(entries) != 0 && !*aclEnableReset {
		return errors.Errorf("ACLs already enabled")
	}

	if *aclEnableReset {
		for _, e := range entries {
			log(ctx).Infof("deleting previous ACL entry %v", e.ManifestID)

			if err := rep.DeleteManifest(ctx, e.ManifestID); err != nil {
				return errors.Wrap(err, "unable to delete previous ACL")
			}
		}
	}

	for _, e := range auth.DefaultACLs {
		if err := acl.AddACL(ctx, rep, e); err != nil {
			return errors.Wrap(err, "unable to add default ACL")
		}
	}

	return nil
}

func init() {
	aclEnableCommand.Action(repositoryWriterAction(runACLEnable))
}
