#!/usr/bin/python
import sys,os,csv,time, subprocess

# Start this script in the /projects/ directory on web.stanford.edu web space
# make sure that projects directory has a+r permissions (chmod a+r projects)

# Expects a file in current directory called teams.csv
# Should be formatted with the following fields:
# studio
# title (this is the team name)
# logins (member1, member2, member3, member4)
# you can directly download from Google Spreadsheets
# and just change the field names

def make_group_data(row):
    group = {}
    group['studio'] = row['studio']
    group['title'] = row['title']
    group['tagline'] = row['tagline']

    # Create logins as list
    logins = []
    logins.append(row['member1'])
    logins.append(row['member2'])
    if (row['member3']):
        logins.append(row['member3'])
    if (row['member4']):
        logins.append(row['member4'])
    group['logins'] = logins
    return group

with open('teams.csv', 'r') as csvfile:
    teamreader = csv.DictReader(csvfile)
    for row in teamreader:
        group = make_group_data(row)
        studio = row['studio']
        title = row['title']
        studio = ('').join(e for e in studio if e.isalpha()) 
        title = ('').join(e for e in title if e.isalpha())
        studio = ('_').join(studio.split())
        title = ('_').join(title.split())

        projectDir = './' + studio + '/' + title

        #create the studio directory if it doesn't exist
        if not os.path.exists(studio): 
            os.system('mkdir %s' %studio)
            print ('Make studio directory for %s' %(studio))

        #change to the studio directory and create the project title directory if it doesn't exist
        os.chdir(studio)
        if not os.path.exists(title): 
            os.system('mkdir %s' % title)

        #give team members permission on their account
        for login in group['logins']:
            print ('Giving %s permission to read/write %s' % (login, projectDir))
            os.system('fs sa ' + title + ' ' + login + ' write')
      
        #change to the project directory, create .htaccess file, and default index.html file      
        #only run this set of 4 lines on hci.stanford.edu class directory
        #os.chdir(title)
        #os.system('echo "redirect /courses/cs147/2018/au/projects/%s/%s http://web.stanford.edu/class/cs147/projects/%s/%s" > .htaccess'%(studio, title, studio, title))
        #os.system('touch index.html')
        #print ('just made htaccess for %s/%s'%(studio, title))

        #return back up to projects directory
        os.chdir('../')

