#!/usr/bin/env python3
import subprocess
import os
from executioner import execute

"""
Subdomains Pull Script

This script sets up the initial folder structure
for the charlesreid1.com subdomains and their content.
"""

SERVER_NAME_DEFAULT = '{{ server_name_default }}'
USERNAME = '{{ username }}'



# Each subdomain page has an htdocs dir at
#
# /www/SUBDOMAIN.charlesreid1.XYZ/htdocs
# 
# and a .git directory at
#
# /www/SUBDOMAIN.charlesreid1.XYZ/git.SUBDOMAIN.charlesreid1.XYZ

# Name of all subdomains to set up
sub_names = ['bots','pages','hooks']
subs = [n+'.'+SERVER_NAME_DEFAULT for n in sub_names]

# Use git.charlesreid1.com
# (Note we have to hard-code the suffix 
#  charlesreid1.com b/c that is the name
#  of the repo for ALL subdomains)
urls = ['https://git.charlesreid1.com/charlesreid1/%s.charlesreid1.com'%(n) for n in sub_names]
# 
# Use github.com (alternative)
# (Note we have to hard-code the suffix charlesreid1.com)
#urls = ['https://github.com/charlesreid1-docker/%s.charlesreid1.com'%(n) for n in sub_names]

# Base directory for all htdocs folders
pth = '/www'

# Create the base directory
subprocess.call(['mkdir','-p',pth])

# Step 1: clone htdocs dir for each subdomain
for subname, sub, url in zip(sub_names,subs,urls):

    # Step 1: pull
    # Construct the git pull command to update
    # the live htdocs directory for this project

    basedir = os.path.join(pth,sub)
    htdocsdir = os.path.join(basedir,"htdocs")
    dotgitdir = os.path.join(basedir,"git.%s"%(subname))

    if not os.path.exists(htdocsdir):
        print("Git repository has not been cloned, %s does not exist on disk!"%(htdocsdir))

    else:

        # git pull, respecting the
        # unusual .git/repo folder layout
        pullcmd = ['git',
                   '-C', basedir,
                   '--git-dir=%s'%(dotgitdir),
                   '--work-tree=%s'%(htdocsdir),
                   'pull','origin','gh-pages']


        print("About to pull htdocs dir for %s using command:\n"%(sub))
        print("    $ " + " ".join(pullcmd))
        print("\n")

        for loo in execute(pullcmd):
            print(loo)
        print("\n")
        print("Done.")



# Step 2: chown
# Construct chown command to chown everybody
chowncmd = ['chown','-R',USERNAME+":"+USERNAME,basedir]

print("About to change owner of %s using command:\n"%(basedir))
print("    $ " + " ".join(chowncmd))
print("\n")

for loo in execute(chowncmd):
    print(loo)
print("\n")

print("Done.")

