#!/usr/bin/env python
# coding=UTF-8
"""
Run when
 - new boxes are added
 - their README.md is changed
"""
from __future__ import print_function, absolute_import, division

import os
import os.path
import sys

PREFIX = 'henrietta/'


def readfile(path, prefix=None, lines=False, strip=True):
    if prefix is not None:
        path = os.path.join(prefix, path)

    with open(path, 'rb') as f:
        if lines:
            d = f.readlines()
            if strip:
                d = [q.strip() for q in d]
        else:
            d = f.read()
            if strip:
                d = d.strip()
        return d


def writefile(content, path, prefix=None, lines=False):
    if prefix is not None:
        path = os.path.join(prefix, path)

    with open(path, 'w' if lines else 'wb') as f:
        if lines:
            f.writelines([q+os.linesep for q in content])
        else:
            if not isinstance(content, list):
                content = [content]
            for piece in content:
                f.write(piece)


if __name__ == '__main__':
    dirs = [dir for dir in os.listdir('.') if os.path.isdir(dir) and (dir not in ('.git', 'example'))]
    exi = lambda box, sup: os.path.exists(os.path.join(box, 'build%s.sh' % (sup,)))
    boxes = [box for box in dirs if exi(box, '') or exi(box, '_as_vagrant')]

    if len(sys.argv) == 1:
        # Generate Gitlab CI file
        gitlabci = []

        for box in boxes:

            readme = readfile('README.md', box, lines=True, strip=True)

            if '---' in readme:
                readme = readme[:readme.index('---')]

            readme = readme + ['---', '', 'Usage in Vagrantfile:', '```',
                               'config.vm.box = "'+PREFIX+box+'"',
                               'config.vm.box_url = "http://dev.dms-serwis.com.pl/vagrant/'+box+'.box"',
                               '```']

            writefile(readme, 'README.md', box, lines=True)

            try:
                os.unlink(os.path.join(box, 'metadata.json'))
            except OSError:
                pass

            gitlabci.append('''
deploy_$BOX:
  stage: deploy
  tags:
    - vagrant
    - develop19216822423
  script:
    - vagrant box remove $PREFIX$BOX || true
    - vagrant box add $PREFIX$BOX file:///var/www/html/dev/vagrant/$BOX.box
build_$BOX:
  stage: build
  tags:
    - vagrant
    - develop19216822423
  before_script:
    - cp *.sh $BOX/
    - cp SkeletonVagrantfile $BOX/Vagrantfile
    - cd $BOX
    - python ../make.py meta
  script:
    - vagrant up
    - vagrant package --out $BOX.box
    - mv -f $BOX.box /var/www/html/dev/vagrant/$BOX.box
    - cd ..
  after_script:
    - vagrant destroy -f
    - cd ..
'''.replace('$BOX', box).replace('$PREFIX', PREFIX).replace('\n', os.linesep))

        if len(gitlabci) == 0:
            gitlabci = ['''check_validity:
  stage: test
  script:
    - python make.py newbox test
    - cd test
    - python ../make.py meta
    - grep "1.0" metadata.json
    - grep "test" metadata.json
    - cd ..
'''.replace('\n', os.linesep)]

        writefile(gitlabci, '.gitlab-ci.yml')

    if ' '.join(sys.argv).endswith('meta'):
        box = os.path.split(os.getcwd())[-1]

        readme = readfile('README.md', lines=True)
        description = readme[2]

        # Try get version
        try:
            version = readme[3]
            if not version.startswith('Version:'):
                raise IndexError()
            version = version.split(':')[1].strip()
        except IndexError:
            version = '1.0'

        writefile('''{
    "description": "$DESCRIPTION",
    "short_description": "$DESCRIPTION",
    "name": "$PREFIX$BOX",
    "versions": [{
        "version": "$VERSION",
        "status": "active",
        "description_html": "<p>$DESCRIPTION</p>",
        "description_markdown": "$DESCRIPTION",
        "providers": [{
            "name": "virtualbox",
            "url": "http://dev.dms-serwis.com.pl/vagrant/$BOX.box"
        }]
    }]
}
'''.replace('$DESCRIPTION', description).replace('$BOX', box).replace('$PREFIX', PREFIX).replace('$VERSION', version),
                  'metadata.json')

    if len(sys.argv) == 3:
        if sys.argv[-2] == 'newbox':
            box = sys.argv[-1]
            os.mkdir(box)
            writefile('''# $BOX

This is description of the box. It will be copied. Keep it short and single-line. Don't remove the line break before.
Version: 1.0

Write what this box consists of and how it behaves.
First four lines have a special meaning - dont move them around. Change only version number, not the word.

---

This section will be automatically replaced by `python make.py` with auto-generated
content of Vagrantfile that will refer to this box.
'''.replace('$BOX', box).replace('$PREFIX', PREFIX).replace('\n', os.linesep), 'README.md', box)

            writefile('''#!/bin/bash

# This will be executed during build process as root
# You can delete it if you want to.
# cd into a directory if you depend on a particular working directory.
''', 'build.sh', box)

            writefile('''#!/bin/bash

# This will be executed during build process as user Vagrant
# You can delete it if you want to.
# cd into a directory if you depend on a particular working directory.
''', 'build_as_vagrant.sh', box)