#!/usr/bin/python
#
# An OBS Source Service to create a helm chart from files installed
# into the build environment (through an RPM dependency)
#
# (C) 2020 SUSE LLC
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# See http://www.gnu.org/licenses/gpl-2.0.html for full license text.
#
"""\
OBS Source Service to create a helm chart from files found in the 
build environment. This helps automate helm chart creation by leveraging
the use of RPM dependencies

The helm chart should resemble the following directory structure:

Chart.yaml
values.yaml
chart_name.tar, which includes:
   templates (directory)
   README.md (optional)

The following _service file (plus an RPM dependency to install the required files)
allows this script to create the above directory structure

<services>
    <service name="chart_helper" mode="buildtime">
    <param name="source">/usr/share/rook-ceph-helm-charts/operator</param>
    <param name="output">rook-helm</param>
    <param name="include">templates</param>
    <param name="include">README.md</param>
    <param name="extract">Chart.yaml</param>
    <param name="extract">values.yaml</param>
  </service>
</services>

"""

import getopt
import sys
import tempfile
import os.path
from os import path
from distutils.dir_util import copy_tree
from shutil import copy, rmtree

def main():
    print 'Running chart_helper to create build directory'
    try:
        opts, args = getopt.getopt(sys.argv[1:], '', ['source=', 'output=', 'include=', 'extract=', 'outdir='])
    except getopt.GetoptError:
        sys.exit(2)
    source = None
    output = None
    outdir = None
    include = []
    extract = []
    for opt, arg in opts:
        if opt in ('--source'):
            if path.exists(arg):
                source = arg
                print ' Source directory: ' + source
            else:
                assert False, 'Source path not found'
        elif opt in ('--output'):
            output = arg + '.tar'
            print ' Output archive: ' + output
        elif opt in ('--include'):
            include.append(arg)
            print ' Including: ' + arg
        elif opt in ('--extract'):
            extract.append(arg)
            print ' Extracting: ' + arg
        elif opt in ('--outdir'):
            outdir = arg
        else:
            assert False, 'Unhandled option'
    if source == None:
         assert False, 'Source path not specified'
    if output == None:
         assert False, 'Output file not specified'
    # setup directories
    build_dir=os.getcwd()
    tmpdir = tempfile.mkdtemp()
    # copy designated files into temp directory
    for inc in include:
        src=os.path.join(source, inc)
        if os.path.isdir(src):
            dst=os.path.join(tmpdir, inc)
            os.mkdir(dst)
            copy_tree(src, dst)
        else:
            copy(src, tmpdir)
    # build output tarball
    os.chdir(tmpdir)
    tarfile=os.path.join(build_dir, output)
    os.system('tar cf ' + tarfile + ' *')
    os.chdir(build_dir)
    rmtree(tmpdir)
    # extract specified files to build_dir
    for ext in extract:
        copy(os.path.join(source, ext), build_dir)
    print 'Finished creating build directory'

if __name__ == '__main__':
    main()
