# 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/'

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:
            ci.write('''
deploy:
  stage: deploy
  tags:
    - vagrant
    - develop19216822423
  script:''')

            for box in boxes:
                ci.write('''
    - vagrant box remove $PREFIX$BOX
    - vagrant box add $PREFIX$BOX file:///var/www/html/dev/vagrant/$BOX.box'''.replace('$BOX', box).replace('$PREFIX', PREFIX))

            ci.write('\n')
            for box in boxes:
                try:
                    os.unlink(os.path.join(box, 'metadata.json'))
                except OSError:
                    pass

                ci.write('''
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))
        # README.md
        index = []
        for box in boxes:
            with open(os.path.join(box, 'README.md'), 'rb') as mdin:
                description = mdin.readlines()[2].strip()

            index.append(
                u'* **$BOX**: [$DESCRIPTION](/$BOX/README.md)\n'.replace('$DESCRIPTION', description).replace('$BOX',
                                                                                                            box).replace(
                    '$PREFIX', PREFIX))

        index = [u'''# vagrant-boxen

**Problem:** installing same things over and over makes builds long

**Solution:** make Vagrant images with common things preinstalled

Boxes are based off *debian/contrib-jessie64*

# How to rebuild

```bash
python make.py
git add --all
git commit -m "dfdf"
git push origin master
```

Boxes are automatically regenerated upon a push to master.
If you want to develop a single box, just make a branch that starts with it's name
and a dash, eg. **cassandra-something**.
Only it will then rebuild upon commit.

Boxes, after being built, will be automatically available at
[http://dev.dms-serwis.com.pl/vagrant/](http://dev.dms-serwis.com.pl/vagrant/)

# Box index

    '''] + index

        with open('README.md', 'wb') as wo:
            wo.write(u''.join(index).encode('utf8'))





    if ' '.join(sys.argv).endswith('meta'):
        box = os.path.split(os.getcwd())[-1]
        with open('README.md', 'rb') as mdin, open('metadata.json', 'wb') as mdout:
            description = mdin.readlines()[2].strip()


            mdout.write('''{
    "description": "$DESCRIPTION",
    "short_description": "$DESCRIPTION",
    "name": "$PREFIX$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', box).replace('$PREFIX', PREFIX))


        with open('README.md', 'rb') as rin:
            readme = rin.read()

        readme = readme + '''Use like:
```
config.vm.box = "$PREFIX$BOX"
config.vm.box_url = "http://dev.dms-serwis.com.pl/vagrant/$BOX.box"
```
'''.replace('$BOX', box).replace('$PREFIX', PREFIX)

        with open('README.md', 'wb') as fo:
            fo.write(readme)