#!/usr/bin/python
# Copyright Cloud Linux Zug GmbH
import shutil

__author__ = 'iseletsk'

import os
import getopt
import sys

BASE_DIR='/usr/share/kcare-eportal/patches/'
LATEST_DIR=BASE_DIR+"release/release-latest/"
PRODUCTION=False


def link_file(name, dir, dest_dir):
    full_name = dest_dir+'/'+name
    if os.path.exists(full_name) and not os.path.islink(full_name):
        os.unlink(full_name)
    if not os.path.exists(full_name):
        try:
            os.symlink(LATEST_DIR+dir+'/'+name, full_name)
        except OSError, e:
            if e.errno == 17:
                pass
            else:
                raise e

def link_dir(dir):
    print "Processing %s" % dir
    dest_dir = BASE_DIR + dir
    src_dir = SOURCE_DIR + dir
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)

    with file(src_dir+'/latest.v1') as f:
        release = f.read()

    release_dir = dest_dir+'/'+release
    if os.path.lexists(release_dir):
        try:
            os.unlink(release_dir)
        except OSError, e:
            if e.errno == 21: #Directory
                shutil.rmtree(release_dir)
            else:
                raise e

    os.symlink(src_dir+'/'+release, release_dir)

    link_file('kcare.ko', dir, dest_dir)
    link_file('kcare.ko.sig', dir, dest_dir)
    link_file('version', dir, dest_dir)
    link_file('latest.v1', dir, dest_dir)

    #do release-latest
    rl_dir=LATEST_DIR+dir
    if os.path.exists(rl_dir) and os.path.islink(rl_dir):
        os.unlink(rl_dir)
    os.symlink(src_dir, rl_dir)

def link_json():
    lpatches = LATEST_DIR + 'patches.json'
    if os.path.exists(lpatches):
        os.unlink(lpatches)
    os.symlink(SOURCE_DIR+'/patches.json', lpatches)
    if not os.path.exists(BASE_DIR+"/patches.json"):
        os.symlink(lpatches, BASE_DIR+"/patches.json")

def process_latest():
    for dir in os.listdir(SOURCE_DIR):
        if os.path.isdir(SOURCE_DIR + dir):
            link_dir(dir)
        link_json()
    print "All Done"

def usage():
    print 'Usage: %s [OPTIONS] release_tag' % (sys.argv[0])
    print
    print 'deploys release RELEASE_TAG as latest release'
    print 'patches for the RELEASE_TAG should be located in ' \
          '/usr/share/kcare-eportal/patches/release/RELEASE_TAG'
    print '-p | --production         : deploy to production, otherwise test assumed'
    print '-h | --help               : show this help'

def main():
    global PRODUCTION
    global BASE_DIR, SOURCE_DIR, LATEST_DIR
    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            'h:p', ['production','help'])
    except getopt.GetoptError, e:
        print "ERROR: %s" %(str(e),)
        usage()
        sys.exit(1)

    for o, a in opts:
        if o in ['-h', '--help']:
            usage()
            sys.exit(0)
        elif o in ['-p', '--production']:
            PRODUCTION=True
    if len(args) <> 1:
        print "RELEASE TAG required"
        usage()
        sys.exit(1)
    if not PRODUCTION:
        BASE_DIR=BASE_DIR+'test/'
    SOURCE_DIR = BASE_DIR + 'release/'+args[0] + '/'
    LATEST_DIR = BASE_DIR + 'release/release-latest/'
    if not os.path.exists(SOURCE_DIR):
        print "%s doesn't exist" % SOURCE_DIR
        sys.exit(1)
    if not os.path.exists(LATEST_DIR):
        try:
            os.makedirs(LATEST_DIR)
        except:
            print "Unable to create %s", LATEST_DIR
            sys.exit(1)
    if PRODUCTION:
        deploy_type = "PRODUCTION"
    else:
        deploy_type = "TESTING"

    print "Deploying to %s, release %s" % (deploy_type, args[0])
    process_latest()


if __name__ == '__main__':
    main()