#!/usr/bin/env python3
import subprocess
import sys
from subprocess import call, check_output
import time
import getpass

# Functions

def mybash(cmd):
  call(cmd, shell=True)
  
def d_clean_all_containers():
  # Remove all docker containers
  mybash("docker stop $(docker ps -a -q) && docker rm $(docker ps -a -q)")

def dc_rebuild(img = ''):
  # https://docs.docker.com/compose/production/#modify-your-compose-file-for-production
  mybash("docker-compose build %s && docker-compose up --no-deps -d %s" % (img, img))

def d_clean():
  # clean stopped containers
  mybash("docker ps -a | grep Exit | cut -d ' ' -f 1 | xargs docker rm")
  # clean unused images
  mybash("docker rmi -f $(docker images -q -a -f dangling=true)")

def d_app_fromscratch(projectname = 'example'):
  d_clean_all_containers()
  # Caution: You might lose all assets of the app
  mybash("docker rmi $(docker images -a -q)")

  # Remove old files
  mybash("rm -r ./app")

  # This instructs Compose to run django-admin.py startproject composeexample in a container, using the web service’s image and configuration.
  mybash("docker-compose run web django-admin.py startproject %s /src" % projectname)

  # If you are running Docker on Linux, the files django-admin created are owned by root. This happens because the container runs as the root user. Change the ownership of the new files.
  mybash("sudo chown -R $USER:$USER .")

  # Edit generated settings.py manually
  #
  # ALLOWED_HOSTS = ['web']
  #
  # DATABASES = {
  #     'default': {
  #         'ENGINE': 'django.db.backends.postgresql_psycopg2',
  #         'NAME': 'postgres',
  #         'USER': 'postgres',
  #         'PASSWORD': 'pgpasswd'
  #         'HOST': 'db',
  #         'PORT': 5432,
  #     }
  # }
  #
  # STATIC_ROOT = '/static/'
  mybash("vi ./app/src/%s/settings.py" % projectname)

  # Edit generated urls.py
  # https://docs.djangoproject.com/en/1.11/howto/static-files/#serving-static-files-during-development
  mybash("vi ./app/src/%s/urls.py" % projectname)

  # create containers
  mybash("docker-compose up -d")

def d_ps(name = None):
  if not name:
    script = "docker ps -a"
  else:
    script = "docker ps -f 'name=%s'" % name
  mybash(script)
  rows = str(check_output(script, shell=True)).split('\\n')
  rows.pop(0)
  # Fiter a row which has more than a letter
  rows = list(filter(lambda r: len(r) > 1, rows))
  containers = []
  for row in rows:
    # Assuming it's ok splitting by double spaces
    cols = row.split('  ')
    containers.append({
      'id': cols[0],
      'image': cols[1],
      'command': cols[2],
      'craeted': cols[3],
      'status': cols[4],
      'ports': cols[5],
      'names': cols[6],
    })
  return containers

# Start
d_clean()

def dc_rebuild_all():
  print("Hint: Try again if it didn't work well")
  dc_rebuild()


_argv = sys.argv
if len(_argv) <= 1:
  dc_rebuild('web')
else:
  if _argv[1] == 'scratch':
    if len(_argv) > 2:
      d_app_fromscratch(_argv[2])
    else:
      d_app_fromscratch()
  elif _argv[1] == 'rebuild':
    if len(_argv) > 2:
      dc_rebuild(len(_argv[2]))
    else:
      dc_rebuild_all()
  elif _argv[1] == 'dev':
    if len(_argv) > 2 and _argv[2] == 'build':
      mybash("docker build -t dev -f dev/Dockerfile .")
    uname = getpass.getuser()
    d = d_ps('%s-dev' % uname)
    # check if the contaienr exists
    if len(d):
      mybash("docker exec -it %s /bin/bash" % d[0]['id'])
    else:
      mybash("docker run --name %s-dev -it dev /bin/bash" % uname)
    # TODO open tmux
    # TODO docker is enabled in dev-env
    # TODO add shared volume -v

time.sleep(6)
d_ps()

##
# Usage:
#   dc_run
#     - rebuild web and run it
#   dc_run scratch <django_project_name>
#     - delete everything then make env and app from scratch
#   dc_run rebuild [all, [docker_image_name]]
#     - rebuild images and run container(s)
#   dc_run dev [build]
#     - run dev container
##

cf63b9a285a9301b23af539cefd26e232ca16f1b
<mask token>


def d_clean_all_containers():
    mybash('docker stop $(docker ps -a -q) && docker rm $(docker ps -a -q)')


def dc_rebuild(img=''):
    mybash('docker-compose build %s && docker-compose up --no-deps -d %s' %
        (img, img))


<mask token>

<mask token>


def d_clean_all_containers():
    mybash('docker stop $(docker ps -a -q) && docker rm $(docker ps -a -q)')


def dc_rebuild(img=''):
    mybash('docker-compose build %s && docker-compose up --no-deps -d %s' %
        (img, img))


<mask token>


def d_ps(name=None):
    if not name:
        script = 'docker ps -a'
    else:
        script = "docker ps -f 'name=%s'" % name
    mybash(script)
    rows = str(check_output(script, shell=True)).split('\\n')
    rows.pop(0)
    rows = list(filter(lambda r: len(r) > 1, rows))
    containers = []
    for row in rows:
        cols = row.split('  ')
        containers.append({'id': cols[0], 'image': cols[1], 'command': cols
            [2], 'craeted': cols[3], 'status': cols[4], 'ports': cols[5],
            'names': cols[6]})
    return containers


<mask token>

<mask token>


def d_clean_all_containers():
    mybash('docker stop $(docker ps -a -q) && docker rm $(docker ps -a -q)')


def dc_rebuild(img=''):
    mybash('docker-compose build %s && docker-compose up --no-deps -d %s' %
        (img, img))


<mask token>


def d_ps(name=None):
    if not name:
        script = 'docker ps -a'
    else:
        script = "docker ps -f 'name=%s'" % name
    mybash(script)
    rows = str(check_output(script, shell=True)).split('\\n')
    rows.pop(0)
    rows = list(filter(lambda r: len(r) > 1, rows))
    containers = []
    for row in rows:
        cols = row.split('  ')
        containers.append({'id': cols[0], 'image': cols[1], 'command': cols
            [2], 'craeted': cols[3], 'status': cols[4], 'ports': cols[5],
            'names': cols[6]})
    return containers


<mask token>


def dc_rebuild_all():
    print("Hint: Try again if it didn't work well")
    dc_rebuild()


<mask token>

<mask token>


def mybash(cmd):
    call(cmd, shell=True)


def d_clean_all_containers():
    mybash('docker stop $(docker ps -a -q) && docker rm $(docker ps -a -q)')


def dc_rebuild(img=''):
    mybash('docker-compose build %s && docker-compose up --no-deps -d %s' %
        (img, img))


def d_clean():
    mybash("docker ps -a | grep Exit | cut -d ' ' -f 1 | xargs docker rm")
    mybash('docker rmi -f $(docker images -q -a -f dangling=true)')


def d_app_fromscratch(projectname='example'):
    d_clean_all_containers()
    mybash('docker rmi $(docker images -a -q)')
    mybash('rm -r ./app')
    mybash('docker-compose run web django-admin.py startproject %s /src' %
        projectname)
    mybash('sudo chown -R $USER:$USER .')
    mybash('vi ./app/src/%s/settings.py' % projectname)
    mybash('vi ./app/src/%s/urls.py' % projectname)
    mybash('docker-compose up -d')


def d_ps(name=None):
    if not name:
        script = 'docker ps -a'
    else:
        script = "docker ps -f 'name=%s'" % name
    mybash(script)
    rows = str(check_output(script, shell=True)).split('\\n')
    rows.pop(0)
    rows = list(filter(lambda r: len(r) > 1, rows))
    containers = []
    for row in rows:
        cols = row.split('  ')
        containers.append({'id': cols[0], 'image': cols[1], 'command': cols
            [2], 'craeted': cols[3], 'status': cols[4], 'ports': cols[5],
            'names': cols[6]})
    return containers


d_clean()


def dc_rebuild_all():
    print("Hint: Try again if it didn't work well")
    dc_rebuild()


_argv = sys.argv
if len(_argv) <= 1:
    dc_rebuild('web')
elif _argv[1] == 'scratch':
    if len(_argv) > 2:
        d_app_fromscratch(_argv[2])
    else:
        d_app_fromscratch()
elif _argv[1] == 'rebuild':
    if len(_argv) > 2:
        dc_rebuild(len(_argv[2]))
    else:
        dc_rebuild_all()
elif _argv[1] == 'dev':
    if len(_argv) > 2 and _argv[2] == 'build':
        mybash('docker build -t dev -f dev/Dockerfile .')
    uname = getpass.getuser()
    d = d_ps('%s-dev' % uname)
    if len(d):
        mybash('docker exec -it %s /bin/bash' % d[0]['id'])
    else:
        mybash('docker run --name %s-dev -it dev /bin/bash' % uname)
time.sleep(6)
d_ps()

#!/usr/bin/env python3
import subprocess
import sys
from subprocess import call, check_output
import time
import getpass

# Functions

def mybash(cmd):
  call(cmd, shell=True)
  
def d_clean_all_containers():
  # Remove all docker containers
  mybash("docker stop $(docker ps -a -q) && docker rm $(docker ps -a -q)")

def dc_rebuild(img = ''):
  # https://docs.docker.com/compose/production/#modify-your-compose-file-for-production
  mybash("docker-compose build %s && docker-compose up --no-deps -d %s" % (img, img))

def d_clean():
  # clean stopped containers
  mybash("docker ps -a | grep Exit | cut -d ' ' -f 1 | xargs docker rm")
  # clean unused images
  mybash("docker rmi -f $(docker images -q -a -f dangling=true)")

def d_app_fromscratch(projectname = 'example'):
  d_clean_all_containers()
  # Caution: You might lose all assets of the app
  mybash("docker rmi $(docker images -a -q)")

  # Remove old files
  mybash("rm -r ./app")

  # This instructs Compose to run django-admin.py startproject composeexample in a container, using the web service’s image and configuration.
  mybash("docker-compose run web django-admin.py startproject %s /src" % projectname)

  # If you are running Docker on Linux, the files django-admin created are owned by root. This happens because the container runs as the root user. Change the ownership of the new files.
  mybash("sudo chown -R $USER:$USER .")

  # Edit generated settings.py manually
  #
  # ALLOWED_HOSTS = ['web']
  #
  # DATABASES = {
  #     'default': {
  #         'ENGINE': 'django.db.backends.postgresql_psycopg2',
  #         'NAME': 'postgres',
  #         'USER': 'postgres',
  #         'PASSWORD': 'pgpasswd'
  #         'HOST': 'db',
  #         'PORT': 5432,
  #     }
  # }
  #
  # STATIC_ROOT = '/static/'
  mybash("vi ./app/src/%s/settings.py" % projectname)

  # Edit generated urls.py
  # https://docs.djangoproject.com/en/1.11/howto/static-files/#serving-static-files-during-development
  mybash("vi ./app/src/%s/urls.py" % projectname)

  # create containers
  mybash("docker-compose up -d")

def d_ps(name = None):
  if not name:
    script = "docker ps -a"
  else:
    script = "docker ps -f 'name=%s'" % name
  mybash(script)
  rows = str(check_output(script, shell=True)).split('\\n')
  rows.pop(0)
  # Fiter a row which has more than a letter
  rows = list(filter(lambda r: len(r) > 1, rows))
  containers = []
  for row in rows:
    # Assuming it's ok splitting by double spaces
    cols = row.split('  ')
    containers.append({
      'id': cols[0],
      'image': cols[1],
      'command': cols[2],
      'craeted': cols[3],
      'status': cols[4],
      'ports': cols[5],
      'names': cols[6],
    })
  return containers

# Start
d_clean()

def dc_rebuild_all():
  print("Hint: Try again if it didn't work well")
  dc_rebuild()


_argv = sys.argv
if len(_argv) <= 1:
  dc_rebuild('web')
else:
  if _argv[1] == 'scratch':
    if len(_argv) > 2:
      d_app_fromscratch(_argv[2])
    else:
      d_app_fromscratch()
  elif _argv[1] == 'rebuild':
    if len(_argv) > 2:
      dc_rebuild(len(_argv[2]))
    else:
      dc_rebuild_all()
  elif _argv[1] == 'dev':
    if len(_argv) > 2 and _argv[2] == 'build':
      mybash("docker build -t dev -f dev/Dockerfile .")
    uname = getpass.getuser()
    d = d_ps('%s-dev' % uname)
    # check if the contaienr exists
    if len(d):
      mybash("docker exec -it %s /bin/bash" % d[0]['id'])
    else:
      mybash("docker run --name %s-dev -it dev /bin/bash" % uname)
    # TODO open tmux
    # TODO docker is enabled in dev-env
    # TODO add shared volume -v

time.sleep(6)
d_ps()

##
# Usage:
#   dc_run
#     - rebuild web and run it
#   dc_run scratch <django_project_name>
#     - delete everything then make env and app from scratch
#   dc_run rebuild [all, [docker_image_name]]
#     - rebuild images and run container(s)
#   dc_run dev [build]
#     - run dev container
##
