/*
 * SonarQube
 * Copyright (C) 2009-2024 SonarSource SA
 * mailto:info AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.sonar.scanner.bootstrap;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.utils.System2;
import org.springframework.context.annotation.Bean;

public class SonarUserHomeProvider {
  private static final Logger LOG = LoggerFactory.getLogger(SonarUserHomeProvider.class);

  private System2 system;

  public SonarUserHomeProvider() {
    this(new System2());
  }

  SonarUserHomeProvider(System2 system) {
    this.system = system;
  }

  @Bean
  public SonarUserHome provide(ScannerProperties scannerProps) {
    Path home = findSonarHome(scannerProps);
    LOG.debug("Sonar User Home: {}", home);
    return new SonarUserHome(home);
  }

  private Path findSonarHome(ScannerProperties props) {
    var home = props.property("sonar.userHome");
    if (home != null) {
      return Paths.get(home).toAbsolutePath();
    }

    home = system.envVariable("SONAR_USER_HOME");

    if (home != null) {
      return Paths.get(home).toAbsolutePath();
    }

    var userHome = Objects.requireNonNull(system.property("user.home"), "The system property 'user.home' is expected to be non null");
    return Paths.get(userHome, ".sonar").toAbsolutePath();
  }

}
