// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.yum;

import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.hosted.node.admin.task.util.file.FileWriter;

import java.nio.file.Path;
import java.util.regex.Pattern;

public class AddYumRepo {
    private static final Pattern REPOSITORY_ID_PATTERN = Pattern.compile("^[a-zA-Z_-]+$");

    private final String repositoryId; // e.g. "platform_rpms-latest"
    private final String name; // e.g. "Platform RPM Latest Repo"
    private final String baseurl;
    private final boolean enabled;

    public AddYumRepo(String repositoryId,
                      String name,
                      String baseurl,
                      boolean enabled) {
        this.repositoryId = repositoryId;
        this.name = name;
        this.baseurl = baseurl;
        this.enabled = enabled;
        validateRepositoryId(repositoryId);
    }

    public boolean converge(TaskContext context) {
        Path path = context.fileSystem().getPath("/etc/yum.repos.d",repositoryId + ".repo");

        FileWriter fileWriter = new FileWriter(path, this::getRepoFileContent)
                .withOwner("root")
                .withGroup("root")
                .withPermissions("rw-r--r--")
                .onlyIfFileDoesNotAlreadyExist();

        return fileWriter.converge(context);
    }

    private String getRepoFileContent() {
        return String.join("\n",
                "# This file was generated by node admin",
                "# Do NOT modify this file by hand",
                "",
                "[" + repositoryId + "]",
                "name=" + name,
                "baseurl=" + baseurl,
                "enabled=" + (enabled ? 1 : 0),
                "gpgcheck=0"
        ) + "\n";
    }

    private static void validateRepositoryId(String repositoryId) {
        if (!REPOSITORY_ID_PATTERN.matcher(repositoryId).matches()) {
            throw new IllegalArgumentException("Invalid repository ID '" + repositoryId + "'");
        }
    }
}

@@ -471,16 +471,19 @@
 %5E%5Ba-zA-Z
+0-9
 _-%5D+$%22);

Allow digits in yum repo id