#!/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 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
#
d=[]
stf=[]
tree=st_tool( "t")
tree=tree.splitlines()
for line in tree:
    l = line.decode('utf-8')
    if l.startswith("DIR: /"):
        l=l.replace("DIR: /","")
        d.append(l)
    if l.startswith("FILE: /"):
        l=l.replace("FILE: /","")
        stf.append(l)

#
# Create Directories on Host
#
for d in d:
    try:
      os.mkdir (st_root+d)
    except:
        pass

#
# Copy Files from ST-Disk
#
for stf in stf:
#      stf=f.replace(st_root[2:],"")
      f=st_root+stf
      print (st_tool( "r "+stf+" "+f))
