#!/usr/bin/env python
# -*- coding: utf-8 -*-

import subprocess
import os
import sys
from optparse import OptionParser

#
# Location of the st_tool Binary
#
st_tool_bin="./st-tool"

#
# Default can be overwriten by Commandline options 
#
st_root="./ST_ROOT"
st_disk="-"


def get_dirs(path):
  dlist=[]
  for path, dirs, files in os.walk(path):
      dlist.append(path[2:])
  return dlist

def list_files(path):
  flist=[]
  for path, dirs, files in os.walk(path):
      for f in files:
          flist.append((path+"/"+f)[2:])
  return flist

def st_tool(cmd):
  stcmd=st_tool_bin+" "+st_disk+" "+cmd
  print (stcmd)
  p = subprocess.Popen(stcmd, stdout=subprocess.PIPE, shell=True)
  (output, err) = p.communicate()
  p_status = p.wait()
  if p_status != 0:
    print ("Command exit status/return code : ", p_status)
    exit (0)
  return output

def readparameter():
    parser = OptionParser(usage="usage: %prog [options] <RootDirectory>",
                          version="%prog 1.0")
    parser.add_option("-r", "--stroot",
                      action="store", # optional because action defaults to "store"
                      dest="st_root",
                      default=st_root,
                      help="Root Directory of the ST-Disk in Hostfilesystem",)
    parser.add_option("-d", "--stdisk",
                      action="store", # optional because action defaults to "store"
                      dest="st_disk",
                      default=st_disk,
                      help="ST-Disk File",)
    (options, args) = parser.parse_args()
    
    if len(args) > 1:
        parser.error("wrong number of arguments")
    if len(args) == 0:
        args.append("/")

    return (options,args)


#
# Main Entry
#
# Get Options and Parmeter
(options,args)=readparameter()

#Options
st_root=options.st_root
st_disk=options.st_disk

#Parameter RootDirectory
root=args[0]

# Some Extrachecks
if root[0]=='.':
    root = root[1:]
if root[0]=='/':
    root = root[1:]
if st_root[-1:] != "/":
    st_root=st_root+"/"

root=st_root+root
print ("----------------")
print ("ST-File: "+st_disk)
print ("ST-RootDir: "+st_root)
print ("RootDir: "+root)
print ("----------------")
#
# Get Files and Directories to copy/create
#
f=list_files( root )
d=get_dirs( root )

#
# Create Directories on ST-Disk
#
for d in d:
    d=d.replace(st_root[2:],"")
    if d != "": 
      st_tool( "d "+d)
#
# Copy Files to ST-Disk
#
for f in f:
      stf=f.replace(st_root[2:],"")
      st_tool( "w "+f+" "+stf)
#
# Just Display the Filetree of the ST-Disk
#
print (st_tool( "t"))
