#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
#
# Univention Corporate Client
#  UCC image removal 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
import glob

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

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

if not os.path.exists(configRegistry['ucc/image/path']):
	print "UCC image path", configRegistry['ucc/image/path'], "does not exist"
	sys.exit(1)

parser = OptionParser()
parser.add_option("-l", "--list-images", action="store_true", dest="listimg", help="List all UCC images currently stored")
parser.add_option("-r", "--remove-image", action="store", dest="removeimg", help="Name of UCC image to be removed (name of spec file in dir, e.g. ucc-desktop.spec")

(options, args) = parser.parse_args()

if not options.listimg and not options.removeimg:
	print "You need to specify either -l or -r"
	print "Run with --help for details"
	sys.exit(0)

if options.listimg:
	images = glob.glob(os.path.join(configRegistry['ucc/image/path'], "*spec"))
	for i in images:
		stream = open(i, "r")
		try:
			spec = yaml.load(stream)
		finally:
			stream.close()
		print os.path.basename(i), ":", spec['title'], "(" +  spec['version'] + ")"
	sys.exit(0)

if options.removeimg:
	if not options.removeimg.endswith(".spec"):
		options.removeimg = options.removeimg + ".spec"

	specfile = os.path.join(configRegistry['ucc/image/path'], options.removeimg)
	
	if not os.path.exists(specfile):
		print "UCC image file", specfile, "does not exist, exiting"
		sys.exit(0)
	
	stream = open(specfile, "r")
	try:
		spec = yaml.load(stream)
	finally:
		stream.close()
	
	for i in ['file-initrd', 'file-kernel', 'file-md5', 'file-reg']:
		filepath = os.path.join(configRegistry['ucc/image/path'], spec[i])
		if os.path.exists(filepath):
			print "Removing", filepath
			os.unlink(filepath)
	
	image_file = os.path.join(configRegistry['ucc/image/path'], spec['file-img'])

	if os.path.exists(image_file):
		print "Removing", image_file
		os.unlink(image_file)

	if image_file.endswith('.xz'):
		image_file=image_file[0:len(image_file)-3]

	if os.path.exists(image_file):
		print "Removing", image_file
		os.unlink(image_file)

	print "Removing", specfile
	os.unlink(specfile)

	joinfile = os.path.join("/usr/lib/univention-install", "95" + spec['file-reg'])
	if os.path.exists(joinfile):
		print "Removing", joinfile
		os.unlink(joinfile)
