#!/usr/bin/env python3

import os
import sys

from dotenv import load_dotenv

load_dotenv()

config = {
    'name': os.getenv('PROJECT_NAME'),
    'branches': {
        'staging': os.getenv('BRANCH_STAGING'),
        'master': os.getenv('BRANCH_MASTER'),
    },
}

push_options = []
for i in range(int(os.getenv('GIT_PUSH_OPTION_COUNT'))):
    # print('GIT_PUSH_OPTION_' + str(i) + ': ' + os.getenv('GIT_PUSH_OPTION_' + str(i)), flush=True)
    push_options.append(os.getenv('GIT_PUSH_OPTION_' + str(i)))

print('Working as user ' + os.environ['USER'] + '.', flush=True)
print('Welcome to ' + os.uname()[1] + '.', flush=True)

(old, new, branch) = sys.stdin.read().split(' ')
branch = branch.split('/')[-1].strip()

git_dir = os.getcwd()

if branch not in config['branches']:
    print('Branch ' + branch + ' is not configured.')
    sys.exit(1)

deploy_root = config['branches'][branch]

if not os.path.exists(deploy_root):
    os.mkdir(deploy_root, 0o750)
    # os.makedirs in python3.2+

if os.path.exists(deploy_root + '/public/maintenance_off.html'):
    os.rename(deploy_root + '/public/maintenance_off.html', deploy_root + '/public/maintenance.html')

print('Deploying branch ' + branch + ' to directory ' + deploy_root + '.', flush=True)
os.system('umask 0022 && git --work-tree=' + deploy_root + ' --git-dir=' + git_dir + ' checkout -f ' + branch)
os.system('umask 0022 && git reset --hard ' + new)

os.chdir(deploy_root)
if 'skip-composer' not in push_options:
    os.system(os.getenv('PATH_TO_PHP') + ' /opt/cpanel/composer/bin/composer install --optimize-autoloader')
if 'skip-migrations' not in push_options:
    os.system(os.getenv('PATH_TO_PHP') + ' artisan migrate --step --force')
if 'skip-npm' not in push_options:
    os.system('npm install')
    os.system('npm run build')
if 'skip-cache' not in push_options:
    os.system(os.getenv('PATH_TO_PHP') + ' artisan config:cache')
    os.system(os.getenv('PATH_TO_PHP') + ' artisan route:cache')
    os.system(os.getenv('PATH_TO_PHP') + ' artisan view:cache')
    os.system(os.getenv('PATH_TO_PHP') + ' artisan optimize:clear')
os.chdir(git_dir)

if os.path.exists(deploy_root + '/public/maintenance.html'):
    os.rename(deploy_root + '/public/maintenance.html', deploy_root + '/public/maintenance_off.html')

print('Done.', flush=True)

