#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
#
# Univention Corporate Client
#  UCC image download tool
#
# Copyright (C) 2012-2013 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

from optparse import OptionParser
import univention.config_registry as ucr

import os
import shutil
import subprocess
import sys
import tempfile
import time
import traceback
import yaml
import hashlib
import commands

configRegistry = ucr.ConfigRegistry()
configRegistry.load()

if not configRegistry['ucc/image/path']:
	print "The UCR variable ucc/image/path must be set"
	sys.exit(1)

image_directory = configRegistry['ucc/image/path']

if not os.path.exists(image_directory):
	print "UCC image path", image_directory, "does not exist"
	sys.exit(1)

def download_file(filename, hashv, validate_hash):
	if options.reload:
		if os.path.exists(image_directory + "/" + filename):
			print filename, "already exists. Removing it, since reload is requested"
			os.remove(image_directory + "/" + filename)

	ret = subprocess.call("/usr/bin/wget " + wget_opts + base_url + filename, shell=True)
	if ret != 0:
		print "An error (", str(ret), ") occured while downloading image", filename
		print "Terminating"
		sys.exit(1)
	if validate_hash:
		print "Verifying hash value"
		digest = commands.getoutput("sha256sum " + image_directory + "/" + filename).split(" ")[0].strip()
		if digest != hashv:
			print "Incorrect hash value of downloaded file! Quitting"
			print "Hash expected:", hashv
			print "Hash received:", digest
			sys.exit(1)


usage = '''%s [options] -c config_file ''' % sys.argv[0]
parser = OptionParser(usage=usage)


parser.add_option("-s", "--specurl", action="store", dest="spec", help="Spec file for the image download (without the URL part of the mirror)")
parser.add_option("-r", "--reload", action="store_true", dest="reload", help="Force reloading of file, do not resume downloads")
parser.add_option("-p", "--set-root-pw-interactive", action="store_true", default=False, dest="rootpw", help="By default the root password from the current system is set in the image. Use this option to set it interactively")
parser.add_option("--skip-hash", action="store_true", default=False, dest="skiphash", help="Skip validation of downloaded files")

(options, args) = parser.parse_args()

if not options.spec:
	print 'ERROR: Missing argument -s spec_file.'
	print parser.print_help()
	sys.exit(1)

if options.skiphash:
	check_hash = False
else:
	check_hash = True

base_url = configRegistry['ucc/image/download/url'] + "/" 

workingdir = tempfile.mkdtemp()
ret = subprocess.call("/usr/bin/wget -P " + workingdir + " " + base_url + options.spec, shell=True)
if ret != 0:
	print "Could not download spec file, error code " + str(ret)
	print "Terminating"
	sys.exit(1)


stream = open(os.path.join(workingdir, options.spec), "r")
try:
	spec = yaml.load(stream)
finally:
	stream.close()

for i in ['title', 'version', 'hash-img', 'hash-kernel', 'hash-initrd', 'hash-md5', 'hash-reg', 'file-img', 'file-initrd', 'file-kernel', 'file-md5', 'file-reg']:
	if not spec[i]:
		print 'Malformed spec file, missing entry', i


vfs = os.statvfs(image_directory)
free_diskspace = vfs.f_frsize * vfs.f_bfree

if (free_diskspace < spec['total-size']):
	print "Not enough free diskspace to download the image"
	print "Needed: ", spec['total-size']
	print "Available: ", free_diskspace
	sys.exit(1)

shutil.copy(os.path.join(workingdir, options.spec), image_directory)

print "Downloading", spec['title'], spec['version']

wget_opts = "-c -P " + image_directory + " " 

imgname = os.path.join(image_directory, spec['file-img'])
img_validation = True
if os.path.exists(imgname):
	print imgname, "already exists. Skipping validation of hash value, since the root password is usually altered."
	img_validation = False
	
if img_validation:
	download_file(spec['file-img'], spec['hash-img'], check_hash)
else:
	download_file(spec['file-img'], spec['hash-img'], False)

subprocess.call("/usr/bin/unxz --keep " + imgname, shell=True)

if imgname.endswith(".xz"):
	imgname = imgname[:-3]

if options.rootpw:
	print "Setting root password in the downloaded image. Please enter the password:"
	cmd = "/usr/sbin/ucc-image-root-password -i " + imgname + " -p"
else:
	print "Setting root password in the image to the root password of the current system"
	cmd = "/usr/sbin/ucc-image-root-password -i " + imgname

ret = subprocess.call(cmd, shell=True)
if ret != 0:
	print "Warning: root password could not be set!"

download_file(spec['file-initrd'], spec['hash-initrd'], check_hash)
download_file(spec['file-md5'], spec['hash-md5'], check_hash)
download_file(spec['file-kernel'], spec['hash-kernel'], check_hash)

if options.reload:
	if os.path.exists("/usr/lib/univention-install/95" + spec['file-reg']):
		print spec['file-reg'], "already exists. Removing it, since reload is requested"
		os.remove("/usr/lib/univention-install/95" + spec['file-reg'])

ret = subprocess.call("/usr/bin/wget -c -P /usr/lib/univention-install " + base_url + spec['file-reg'], shell=True)
os.rename("/usr/lib/univention-install/" + spec['file-reg'], "/usr/lib/univention-install/95" + spec['file-reg'])

if ret != 0:
	print "An error (", str(ret), ") occured while downloading image", spec['file-reg']
	print "Terminating"
	sys.exit(1)

subprocess.call("chmod a+x /usr/lib/univention-install/95" + spec['file-reg'], shell=True)

systemrole = configRegistry['server/role']
if systemrole == "domaincontroller_master" or systemrole == "domaincontroller_backup":
	subprocess.call("/usr/lib/univention-install/95" + spec['file-reg'], shell=True)

if not options.skiphash:
	print "Verifying hash value"
	digest = commands.getoutput("sha256sum /usr/lib/univention-install/95" + spec['file-reg']).split(" ")[0].strip()
	if digest != spec['hash-reg']:
		print "Incorrect hash value of downloaded file! Quitting"
		print "Hash expected:", spec['hash-reg']
		print "Hash received:", digest
		sys.exit(1)
