"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.

"""

import os
import tempfile
import re
from .generic_manager import GenericManager, GenericManagerProperties
from .apt_parser import AptParser

from ambari_commons.constants import AMBARI_SUDO_BINARY
from ambari_commons import shell
from resource_management.core.logger import Logger


def replace_underscores(function_to_decorate):
  def wrapper(*args, **kwargs):
    self = args[0]
    name = args[1].replace("_", "-")
    return function_to_decorate(self, name, *args[2:], **kwargs)
  return wrapper


class AptManagerProperties(GenericManagerProperties):
  """
  Class to keep all Package-manager depended properties
  """
  locked_output = "Unable to lock the administration directory"
  repo_error = "Failure when receiving data from the peer"

  repo_manager_bin = "/usr/bin/apt-get"
  repo_cache_bin = "/usr/bin/apt-cache"
  pkg_manager_bin = "/usr/bin/dpkg"
  repo_update_cmd = [repo_manager_bin, 'update', '-qq']

  available_packages_cmd = [repo_cache_bin, "dump"]
  installed_packages_cmd = ['COLUMNS=999', pkg_manager_bin, "-l"]

  repo_definition_location = "/etc/apt/sources.list.d"

  install_cmd = {
    True: [repo_manager_bin, '-o', "Dpkg::Options::=--force-confdef", '--allow-unauthenticated', '--assume-yes', 'install'],
    False: [repo_manager_bin, '-q', '-o', "Dpkg::Options::=--force-confdef", '--allow-unauthenticated', '--assume-yes', 'install']
  }

  remove_cmd = {
    True: [repo_manager_bin, '-y', 'remove'],
    False: [repo_manager_bin, '-y', '-q', 'remove']
  }

  verify_dependency_cmd = [repo_manager_bin, '-qq', 'check']

  install_cmd_env = {'DEBIAN_FRONTEND': 'noninteractive'}

  repo_url_exclude = "ubuntu.com"
  configuration_dump_cmd = [AMBARI_SUDO_BINARY, "apt-config", "dump"]


class AptManager(GenericManager):