import sys
import os

env_to_deploy = False
version_to_deploy = False
env = ""
version = ""
trigger_type = sys.argv[1]
print(f"trigger type: {trigger_type}")
if trigger_type == "workflow_dispatch":
    print("ignore the commit message, continue..")
    exit(0)

if trigger_type == "push":
    commit_message = sys.argv[2]
    split_commit = commit_message.split(" ")
    for word in split_commit:
        if "#deploy_to:" in word:
            split_word = word.split(":")
            env = split_word[1]
            os.system(f"echo 'ENV_NAME={env}' >> $GITHUB_ENV")
            env_to_deploy = True
        elif "#version:" in word:
            split_word = word.split(":")
            version = split_word[1]
            os.system(f"echo 'CONTAINER_TO_DEPLOY={version}' >> $GITHUB_ENV")
            version_to_deploy = True

    if env_to_deploy:
        os.system(f"echo 'BUILD_FROM_SCRATCH=true' >> $GITHUB_ENV")
        print(f"got from commit message env to deploy: {env}")
        if version_to_deploy:
            os.system(f"echo 'BUILD_FROM_SCRATCH=false' >> $GITHUB_ENV")
            print(f"got from commit message version to deploy: {version}")
    else:
        print(f"ERROR: triggered by {trigger_type} and not #deploy_to:<env name> in the commit message. exiting!")
        exit(1)
