#!/usr/bin/env python

UPLOAD = "fedorapeople.org:/project/cockpit/images/"

import argparse
import os
import subprocess
import sys

from common import testinfra

BASE = os.path.dirname(__file__)
IMAGES = os.path.join(BASE, "images")
DATA = os.path.join(os.environ.get("TEST_DATA", BASE), "images")

def upload(store, source):
    name = os.path.basename(source)

    # Compress the image
    compressed = source + ".xz"
    with open(compressed, "w") as fp:
        xz = [ "xz", "--force", "--keep", "--verbose", "--stdout", "--threads=0", source ]
        subprocess.check_call(xz, stdout=fp)

    # And upload the compressed version
    dest = os.path.join(store, name + ".xz")
    subprocess.check_call(["rsync", "--progress", compressed, dest])

    # Remove the compressed version
    os.unlink(compressed)

def prune(store):
    # Get a list of all currently in use files
    current = []
    for filename in os.listdir(IMAGES):
        path = os.path.join(IMAGES, filename)
        if os.path.islink(path):
            current.append(os.readlink(path))

    # Get remote list of files order than the given date
    (host, unused, path) = store.partition(":")
    cmd = ["ssh", host, "--", "find", path, "-name", "'*.xz'", "-mtime", "+{0}".format(testinfra.IMAGE_EXPIRE), "-print0"]
    output = subprocess.check_output(cmd)

    remove = []
    for path in output.strip('\0').split('\0'):
        for name in current:
            if name in path:
                break
        else:
            remove.append(path)

    cmd = ["ssh", host, "--", "rm", "-vf" ] + remove
    subprocess.check_call(cmd)

def main():
    parser = argparse.ArgumentParser(description='Upload virtual machine images')
    parser.add_argument("--store", default=UPLOAD, help="Where to send images")
    parser.add_argument("--prune", action='store_true', help="Remove unused images from the image store first")
    parser.add_argument('image', nargs='*')
    args = parser.parse_args()

    if args.prune:
        prune(args.store)

    sources = []
    for image in args.image:
        link = os.path.join(IMAGES, image)
        if not os.path.islink(link):
            parser.error("image link does not exist: " + image)
        source = os.path.join(DATA, os.readlink(link))
        if not os.path.isfile(source):
            parser.error("image does not exist: " + image)
        sources.append(source)

    for source in sources:
        upload(args.store, source)

if __name__ == '__main__':
    sys.exit(main())
