// Copyright (C) 2017 The Android Open Source Project
//
// 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 com.google.gerrit.server.account;

import static com.google.gerrit.server.config.ScheduleConfig.MISSING_CONFIG;

import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.ScheduleConfig;
import com.google.gerrit.server.git.WorkQueue;
import com.google.gerrit.server.query.account.AccountPredicates;
import com.google.gerrit.server.query.account.InternalAccountQuery;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Runnable to enable scheduling account deactivations to run periodically */
public class AccountDeactivator implements Runnable {
  private static final Logger log = LoggerFactory.getLogger(AccountDeactivator.class);

  public static class Module extends LifecycleModule {
    @Override
    protected void configure() {
      listener().to(Lifecycle.class);
    }
  }

  static class Lifecycle implements LifecycleListener {
    private final WorkQueue queue;
    private final AccountDeactivator deactivator;
    private final boolean supportAutomaticAccountActivityUpdate;
    private final ScheduleConfig scheduleConfig;

    @Inject
    Lifecycle(WorkQueue queue, AccountDeactivator deactivator, @GerritServerConfig Config cfg) {
      this.queue = queue;
      this.deactivator = deactivator;
      scheduleConfig = new ScheduleConfig(cfg, "accountDeactivation");
      supportAutomaticAccountActivityUpdate =
          cfg.getBoolean("auth", "autoUpdateAccountActiveStatus", false);
    }

    @Override
    public void start() {
      if (!supportAutomaticAccountActivityUpdate) {
        return;
      }
      long interval = scheduleConfig.getInterval();
      long delay = scheduleConfig.getInitialDelay();
      if (delay == MISSING_CONFIG && interval == MISSING_CONFIG) {
        log.info("Ignoring missing accountDeactivator schedule configuration");
      } else if (delay < 0 || interval <= 0) {
        log.warn(
            String.format(
                "Ignoring invalid accountDeactivator schedule configuration: %s", scheduleConfig));
      } else {
        queue
            .getDefaultQueue()
            .scheduleAtFixedRate(deactivator, delay, interval, TimeUnit.MILLISECONDS);
      }
    }

    @Override
    public void stop() {
      // handled by WorkQueue.stop() already
    }
  }

  private final Provider<InternalAccountQuery> accountQueryProvider;
  private final Realm realm;
  private final SetInactiveFlag sif;

  @Inject
  AccountDeactivator(
      Provider<InternalAccountQuery> accountQueryProvider, SetInactiveFlag sif, Realm realm) {
    this.accountQueryProvider = accountQueryProvider;
    this.sif = sif;
    this.realm = realm;
  }

  @Override
  public void run() {
    log.debug("Running account deactivations");
    try {
      int numberOfAccountsDeactivated = 0;
      for (AccountState acc : accountQueryProvider.get().query(AccountPredicates.isActive())) {
        log.debug("processing account " + acc.getUserName());
        if (acc.getUserName() != null && !realm.isActive(acc.getUserName())) {
          sif.deactivate(acc.getAccount().getId());
          log.debug("deactivated accout " + acc.getUserName());
          numberOfAccountsDeactivated++;
        }
      }
      log.info(
          "Deactivations complete, {} account(s) were deactivated", numberOfAccountsDeactivated);
    } catch (Exception e) {
      log.error("Failed to deactivate inactive accounts " + e.getMessage(), e);
    }
  }

  @Override
  public String toString() {
    return "account deactivator";
  }
}

@@ -3555,21 +3555,20 @@
     log.
-debug
+info
 (%22Runnin
@@ -3739,32 +3739,418 @@
 ctive())) %7B%0A    
+    if (processAccount(acc)) %7B%0A          numberOfAccountsDeactivated++;%0A        %7D%0A      %7D%0A      log.info(%0A          %22Deactivations complete, %7B%7D account(s) were deactivated%22, numberOfAccountsDeactivated);%0A    %7D catch (Exception e) %7B%0A      log.error(%22Failed to complete deactivation of accounts: %22 + e.getMessage(), e);%0A    %7D%0A  %7D%0A%0A  private boolean processAccount(AccountState account) %7B%0A
     log.debug(%22p
@@ -4166,32 +4166,36 @@
  account %22 + acc
+ount
 .getUserName());
@@ -4193,24 +4193,32 @@
 rName());%0A  
+  try %7B%0A
       if (ac
@@ -4214,24 +4214,28 @@
      if (acc
+ount
 .getUserName
@@ -4263,24 +4263,28 @@
 isActive(acc
+ount
 .getUserName
@@ -4298,18 +4298,16 @@
         
-  
 sif.deac
@@ -4316,16 +4316,20 @@
 vate(acc
+ount
 .getAcco
@@ -4340,26 +4340,24 @@
 ).getId());%0A
-  
         log.
@@ -4356,21 +4356,20 @@
     log.
-debug
+info
 (%22deacti
@@ -4379,16 +4379,17 @@
 ed accou
+n
 t %22 + ac
@@ -4389,16 +4389,20 @@
  %22 + acc
+ount
 .getUser
@@ -4422,58 +4422,56 @@
     
-  numberOfAccountsDeactivated++;%0A        %7D%0A      %7D
+return true;%0A      %7D%0A    %7D catch (Exception e) %7B
 %0A   
@@ -4469,36 +4469,37 @@
  e) %7B%0A      log.
-info
+error
 (%0A          %22Dea
@@ -4487,33 +4487,39 @@
 ror(%0A          %22
-D
+Error d
 eactivations com
@@ -4515,198 +4515,169 @@
 vati
-ons complete, %7B%7D account(s) were deactivated%22, numberOfAccountsDeactivated);%0A    %7D catch (Exception e) %7B%0A      log.error(%22Failed to deactivate inactive accounts %22 + e.getMessage(), e);%0A    %7D
+ng account: %7B%7D (%7B%7D) %7B%7D%22,%0A          account.getUserName(),%0A          account.getAccount().getId(),%0A          e.getMessage(),%0A          e);%0A    %7D%0A    return false;
 %0A  %7D

Allow deactivation loop to continue running after an error