# coding=UTF-8

from __future__ import print_function, absolute_import, division
import os
import os.path
import sys

if __name__ == '__main__':
    dirs = [dir for dir in os.listdir('.') if os.path.isdir(dir) or (dir != '.git')]
    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
        with open('.gitlab-ci.yml', 'wb') as ci:
            for box in boxes:
                ci.write(b'''
build_$BOX:
  only:
    - master
    - /^$BOX\-(.*)$/
  stage: build
  tags:
    - vagrant
    - develop19216822423
  before_script:
    - python make.py meta
    - cp *.sh $BOX/
    - cp SkeletonVagrantfile $BOX/Vagrantfile
    - cd $BOX
  script:
    - vagrant up
    - vagrant package --out $BOX.box
    - mv -f $BOX.box /var/www/html/dev/vagrant/$BOX.box
    - vagrant box remove $PREFIX/$BOX
    - vagrant box add $PREFIX/$BOX file:///var/www/html/dev/vagrant/$BOX.box
    - cd ..
  after_script:
    - vagrant destroy -f
    - cd ..
'''.replace('$BOX', box).replace('$PREFIX', 'henrietta/'))

    if ' '.join(sys.argv).endswith('meta'):

        with open('DESCRIPTION', 'rb') as mdin, open('metadata.json', 'wb') as mdout:
            description = mdin.read().strip()

            mdout.write('''{
    "description": "$DESCRIPTION",
    "short_description": "$DESCRIPTION",
    "name": "henrietta/$BOX",
    "versions": [{
        "version": "1",
        "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', os.path.split(os.getcwd())[-1]))