#!/usr/bin/env python3.1

import os
import sys
import hashlib

# Global Variables

_uw = os.environ['HOME'] + "/.uw"   # The directory where settings are stored
_host = _uw + "/host"               # The host configuration file

# Function Definitions

# Gets or sets the current remote host
def host(args = []):
    if len(args) > 0:
        with open(_host, 'wt') as hostfile:
            hostfile.write(args[0])
            return args.pop(0)
    else:
        with open(_host, 'rt') as hostfile:
            return hostfile.readline()

# Gets or sets the current directory's remote directory
def rdir(args = []):
    rfile = _uw + '/' + hashlib.sha1(str.encode(os.getcwd())).hexdigest()
    if (len(args) > 0) or (not os.path.isfile(rfile)):
        with open(rfile, 'wt') as file:
            file.write(args[0])
            return args.pop(0)
    else:
        with open(rfile, 'rt') as file:
            return file.readline()

# Main

# Verify that the settings directory exists
if not os.path.isdir(_uw):
    os.mkdir(_uw)

# Verify that the host configuration file exists
if not os.path.isfile(_host):
    with open(_host, 'wt') as hostfile:
        hostfile.write('localhost')
        
args = sys.argv[1:] # Obtain a list of arguments.

# The map of commands which may be used as arguments.
commands = {
    'host': lambda: print(host(args)),
    'connect': lambda: os.system('ssh -Y ' + host()),
    'pull': lambda: os.system('rsync -rul --delete ' + host() + ':' + rdir(args) + '/. .'),
    'push': lambda: os.system('rsync -rul --delete . ' + host() + ':' + rdir(args))
}
commands.get(args.pop(0), lambda: print("Command not found."))()
