import urllib2
import sys
import os
import errno
import logging

from parallels.common import run_and_check_local_command

logger = logging.getLogger(__name__)

def install():
	"""Install imapsync package on CentOS 5, advise how to install it on other CentOS releases"""
	if _is_centos_5():
		if _is_package_installed("imapsync"):
			logger.info(u"Package 'imapsync' is already installed")
			return

		if not _is_package_installed("epel-release"):
			repo_filename="/tmp/epel-release-5-4.noarch.rpm"
			if sys.maxsize > 2**32:	# 64bit system
				repo_url = "http://dl.fedoraproject.org/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm"
			else:
				repo_url = "http://dl.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm"
			src = urllib2.urlopen(repo_url)
			with open(repo_filename, "w") as dst:
				dst.write(src.read())

			run_and_check_local_command(["rpm", "-Uhv", repo_filename])
			os.remove(repo_filename)

		run_and_check_local_command(["yum", "-y", "install", "imapsync"])
		logger.info(u"Package 'imapsync' is installed successfully")
	else:
		logger.info(
u"""
To install imapsync on RHEL 5, follow the instructions below:
1. Install EPEL repository by running the following command:
  On 32-bit OSes:
  # rpm -ihv http://dl.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm
  On 64-bit OSes:
  # rpm -ihv http://dl.fedoraproject.org/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
2. Install imapsync from the EPEL repository:
  # yum install imapsync

To install imapsync on CentOS 6 or RHEL 6, follow the instructions below:
1. Install EPEL repository by running the following command:
  On 32-bit OSes:
  # rpm -ihv http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
  On 64-bit OSes:
  # rpm -ihv http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
2. For RHEL 6, install 'perl-File-Copy-Recursive' package from CentOS 6 repository:
  # rpm -ihv http://mirror.centos.org/centos/6/os/i386/Packages/perl-File-Copy-Recursive-0.38-4.el6.noarch.rpm
3. Install imapsync from the EPEL repository:
  # yum install imapsync
"""
		)

def _is_package_installed(pkg_name):
	stdout, _ = run_and_check_local_command(["rpm", "-qa", "--queryformat=%{NAME}\n"])
	return pkg_name in stdout.split()

def _is_centos_5():
	try:
		with open("/etc/redhat-release") as release_info:
			return release_info.read().startswith("CentOS release 5")
	except IOError as e:
		if e.errno == errno.ENOENT:
			return False
		else:
			raise 

