#!/usr/bin/python3

"""
    This hook happens before push
    
    This hook runs diff sql file generated during commit
    Into branch database in branch server

    If this hook fails push also fails
"""

import sys
import os
import socket
import subprocess
from util import diff_file_path, get_exec_data, pg_apply, color, get_branch_name, get_commit_hash, get_stdin_input, extract_branch_name, cmd

# Get exec data
command, input = get_exec_data('DEV_PRE_PUSH_HOOK')

# Extract input and get source branch and target branch
source_branch, _, target_branch, _ = input
source_branch = extract_branch_name(source_branch)
target_branch = extract_branch_name(target_branch)

# Get what branch is active (it differs from source branch)
current_branch = get_branch_name()

# Disable pushing in master or in staging branches
if target_branch=='master' or target_branch=='staging' or target_branch=='main':
    print(color.red('Pushing directly to remote'), color.yellow(target_branch), color.red('not allowed'))
    sys.exit(1)

# Disable pushing from different branch other than current
if source_branch!=current_branch and target_branch!=current_branch:
    print(color.red('You can only push to'), color.yellow(current_branch))
    sys.exit(1)

# Apply diff to branch database
pg_apply(pg_to_env='pg_branch', 
         pg_to_db=target_branch, 
         pg_sql_file=diff_file_path('push', exit_if_absent=True, local=False))

