#!/usr/bin/python
# -*- Mode: Python; indent-tabs-mode: nil; tab-width: 4 -*-
#
# Copyright 2010 Canonical Ltd
# Authors:
#   Michael Terry <michael.terry@canonical.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os, re, subprocess, sys

def regget(path, key):
    regline = subprocess.Popen(["reglookup", "-H", "-p", key, path], stdout=subprocess.PIPE).communicate()[0]
    if not regline:
        return None
    fields = regline.split(',')
    if len(fields) < 3:
        return None
    return fields[2]

def setvar(path, var, val):
    try:
        f = open(path, 'r')
        s = f.read()
        f.close()
    except:
        s = ''

    s, num = re.subn('(^|\n)%s=".*"' % var, '\\1%s="%s"' % (var, val), s)
    if num == 0:
        s += '\n%s="%s"' % (var, val)

    f = open(path, 'w')
    f.write(s)
    f.close()

# Grab winuser and linuser
winuser = subprocess.Popen(['cat', '/var/lib/omsk/winuser'], stdout=subprocess.PIPE).communicate()[0].strip()
linuser = subprocess.Popen(['cat', '/var/lib/omsk/linuser'], stdout=subprocess.PIPE).communicate()[0].strip()
if not winuser or not linuser:
    sys.exit(0)

# Only mount media if we were told to.  And default to not mounting.
mount_media = subprocess.Popen(['sh', '-c', '. /media/private/windows/webnow.sh; echo -n $WEBNOW_MOUNT_MEDIA'], stdout=subprocess.PIPE).communicate()[0].strip()
if mount_media != 'True':
    sys.exit(0)

def getdir(regfile, name, user):
    userdir = regget(regfile, '/Software/Microsoft/Windows/CurrentVersion/Explorer/User Shell Folders/%s' % name)
    if not userdir:
        return None
    if not user:
        user = 'Public'
    userdir = userdir.replace('\\x5C', '/') # encoded backslash
    userdir = userdir.replace('%USERPROFILE%', '/media/private/windows/Users/%s' % user)
    return userdir

def getuserdir(user, name):
    if user:
        regfile = '/media/private/windows/Users/%s/NTUSER.DAT' % user
    else:
        regfile = '/media/private/windows/Windows/System32/config/DEFAULT'
        if not os.path.exists(regfile):
            # use capitals for windows dir
            regfile = '/media/private/windows/WINDOWS/System32/config/DEFAULT'
    return getdir(regfile, name, user)

def shortname(userdir):
    if not userdir: return None
    split = userdir.rsplit('/', 1)
    return split[1] if len(split) >= 2 else userdir

musicdir = getuserdir(winuser, 'My Music')
picdir = getuserdir(winuser, 'My Pictures')
viddir = getuserdir(winuser, 'My Video')
deskdir = getuserdir(winuser, 'Desktop')
docdir = getuserdir(winuser, 'Personal')
# This is the standard name for the download folder apparently:
# http://msdn.microsoft.com/en-us/library/bb882665.aspx
#downdir = getuserdir(winuser, '{374DE290-123F-4565-9164-39C4925E467B}')
# TODO templates and public folders?

# Public user doesn't have its own registry
pubmusicdir = getuserdir(None, 'My Music')
pubpicdir = getuserdir(None, 'My Pictures')
pubviddir = getuserdir(None, 'My Video')

# set dirs in linux land
configdir = '/home/%s/.config' % linuser
dirsfile = os.path.join(configdir, 'user-dirs.dirs')

def makedirs(d):
    try:
        os.system('mkdir -p "%s"' % d)
        os.system('chown %s "%s"' % (linuser, d))
    except OSError:
        pass

def setuserdir(key, userdir):
    name = shortname(userdir)
    setvar(dirsfile, 'XDG_%s_DIR' % key, '$HOME/%s' % name)

# We're not done.  Now we have to actually bindmount the directories
def mountdir(userdir, pubdir = None):
    name = shortname(userdir)
    pubname = shortname(pubdir)
    makedirs('/home/%s/%s' % (linuser, name))
    os.system('mount -B "%s" "/home/%s/%s"' % (userdir, linuser, name))

    if pubname:
        # Now we check the Public user for any sample media and bindmount that in as well
        # Except we can't just assume the directory is called 'Sample Pictures'
        # (might be translated), so we look for the first directory in Public's
        # media dir.
        alldirs = os.listdir(pubdir)
        alldirs = [x for x in alldirs if os.path.isdir('%s/%s' % (pubdir, x))]
        if alldirs:
            sampledir = alldirs[0] # I hope
            linuserdir = '/home/%s/%s/%s' % (linuser, pubname, sampledir)
            makedirs(linuserdir)
            os.system('mount -B "%s/%s" "%s"' % (pubdir, sampledir, linuserdir))
            os.system('echo "%s" >> /var/lib/omsk/mediadirs' % linuserdir)

makedirs(configdir)

# This tells the system to use the directories we bind mount
setuserdir('MUSIC', musicdir)
setuserdir('PICTURES', picdir)
setuserdir('VIDEOS', viddir)
#setuserdir('DESKTOP', deskdir)
# Don't do downloads, since we mount read-only and user wouldn't be able
# to save anything.  We could optionally mount it to a different dir.
#setuserdir('DOWNLOAD', downdir)
#setuserdir('DOCUMENTS', docdir)

os.system('chown %s "%s"' % (linuser, dirsfile))

#   if ubulocale:
#       os.system('echo "%s" > %s/user-dirs.locale' % (ubulocale, configdir))

os.system('rm -f /var/lib/omsk/mediadirs')
os.system('touch /var/lib/omsk/mediadirs')
os.system('chmod o-r /var/lib/omsk/mediadirs')
mountdir(musicdir, pubmusicdir)
mountdir(picdir, pubpicdir)
mountdir(viddir, pubviddir)
#mountdir(deskdir)
#mountdir(docdir)
#mountdir(downdir)
