<commit_before>#!/bin/bash -e

source "$(dirname "${BASH_SOURCE[0]}")/util.bash"

#############################
# CLOUD-FORMATION UTILITIES #
#############################

function getStackIDByName()
{
    local -r stackName="${1}"

    checkNonEmptyString "${stackName}" 'undefined stack name'

    aws cloudformation describe-stacks \
        --output 'text' \
        --query 'Stacks[*].[StackId]' \
        --stack-name "${stackName}" \
    2> '/dev/null' || true
}

#################
# EC2 UTILITIES #
#################

function getLatestAMIIDByAMINamePattern()
{
    local -r amiNamePattern="${1}"

    checkNonEmptyString "${amiNamePattern}" 'undefined ami name pattern'

    aws ec2 describe-images \
        --filters "Name=architecture,Values=x86_64" \
                  "Name=image-type,Values=machine" \
                  "Name=is-public,Values=false" \
                  "Name=state,Values=available" \
                  "Name=name,Values=${amiNamePattern}" \
        --query 'sort_by(Images, &CreationDate)[-1].ImageId' |
    jq \
        --compact-output \
        --raw-output \
        '. // empty'
}

function getInstanceAvailabilityZone()
{
    curl -s --retry 12 --retry-delay 5 'http://instance-data/latest/meta-data/placement/availability-zone'
}

function getInstanceID()
{
    curl -s --retry 12 --retry-delay 5 'http://instance-data/latest/meta-data/instance-id'
}

function getInstanceRegion()
{
    local -r availabilityZone="$(getInstanceAvailabilityZone)"

    checkNonEmptyString "${availabilityZone}" 'undefined availabilityZone'

    echo "${availabilityZone:0:${#availabilityZone} - 1}"
}

function getKeyPairFingerPrintByName()
{
    local -r keyPairName="${1}"

    checkNonEmptyString "${keyPairName}" 'undefined key pair name'

    aws ec2 describe-key-pairs \
        --key-name "${keyPairName}" 2> '/dev/null' |
    jq \
        --compact-output \
        --raw-output \
        '.["KeyPairs"] | .[0] | .["KeyFingerprint"] // empty'
}

function getSecurityGroupIDByName()
{
    local -r securityGroupName="${1}"

    checkNonEmptyString "${securityGroupName}" 'undefined security group name'

    aws ec2 describe-security-groups \
        --filters "Name=group-name,Values=${securityGroupName}" |
    jq \
        --compact-output \
        --raw-output \
        '.["SecurityGroups"] | .[0] | .["GroupId"] // empty'
}

function getSecurityGroupIDsByNames()
{
    local -r securityGroupNames=("${@}")

    local securityGroupID=''
    local securityGroupIDs=''
    local securityGroupName=''

    for securityGroupName in "${securityGroupNames[@]}"
    do
        securityGroupID="$(getSecurityGroupIDByName "${securityGroupName}")"

        checkNonEmptyString "${securityGroupID}" "security group name '${securityGroupName}' not found"

        securityGroupIDs="$(printf '%s\n%s' "${securityGroupIDs}" "${securityGroupID}")"
    done

    echo "${securityGroupIDs}"
}

function revokeSecurityGroupIngress()
{
    local -r securityGroupID="${1}"
    local -r securityGroupName="${2}"

    checkNonEmptyString "${securityGroupID}" 'undefined security group ID'
    checkNonEmptyString "${securityGroupName}" 'undefined security group name'

    local -r ipPermissions="$(
        aws ec2 describe-security-groups \
            --filters "Name=group-name,Values=${securityGroupName}" |
        jq \
            --compact-output \
            --raw-output \
            '.["SecurityGroups"] | .[0] | .["IpPermissions"] // empty'
    )"

    if [[ "$(isEmptyString "${ipPermissions}")" = 'false' && "${ipPermissions}" != '[]' ]]
    then
        aws ec2 revoke-security-group-ingress \
            --group-id "${securityGroupID}" \
            --ip-permissions "${ipPermissions}"
    fi
}

function updateInstanceName()
{
    local -r instanceName="${1}"

    header 'UPDATING INSTANCE NAME'

    checkNonEmptyString "${instanceName}" 'undefined instance name'

    info "${instanceName}"

    aws ec2 create-tags \
        --region "$(getInstanceRegion)" \
        --resources "$(getInstanceID)" \
        --tags "Key='Name',Value='${instanceName}'"
}

#####################
# GENERAL UTILITIES #
#####################

function checkValidRegion()
{
    local -r region="${1}"

    if [[ "$(isValidRegion "${region}")" = 'false' ]]
    then
        fatal "\nFATAL : invalid region '${region}'"
    fi
}

function getAllowedRegions()
{
    echo 'ap-northeast-1 ap-northeast-2 ap-south-1 ap-southeast-1 ap-southeast-2 eu-central-1 eu-west-1 sa-east-1 us-east-1 us-east-2 us-west-1 us-west-2'
}

function getRegionFromRecordSetAliasTargetDNSName()
{
    local -r recordSetAliasTargetDNSName="${1}"

    # Regions

    local -r allowedRegions=($(getAllowedRegions))
    local region=''

    for region in "${allowedRegions[@]}"
    do
        if [[ "$(grep -F -i -o "${region}" <<< "${recordSetAliasTargetDNSName}")" != '' ]]
        then
            echo "${region}" && return 0
        fi
    done
}

function isValidRegion()
{
    local -r region="${1}"

    local -r allowedRegions=($(getAllowedRegions))

    isElementInArray "${region}" "${allowedRegions[@]}"<commit_msg>update lib<commit_after>#!/bin/bash -e

source "$(dirname "${BASH_SOURCE[0]}")/util.bash"

#############################
# CLOUD-FORMATION UTILITIES #
#############################

function getStackIDByName()
{
    local -r stackName="${1}"

    checkNonEmptyString "${stackName}" 'undefined stack name'

    aws cloudformation describe-stacks \
        --output 'text' \
        --query 'Stacks[*].[StackId]' \
        --stack-name "${stackName}" \
    2> '/dev/null' || true
}

#################
# EC2 UTILITIES #
#################

function getLatestAMIIDByAMINamePattern()
{
    local -r amiNamePattern="${1}"

    checkNonEmptyString "${amiNamePattern}" 'undefined ami name pattern'

    aws ec2 describe-images \
        --filters "Name=architecture,Values=x86_64" \
                  "Name=image-type,Values=machine" \
                  "Name=is-public,Values=false" \
                  "Name=state,Values=available" \
                  "Name=name,Values=${amiNamePattern}" \
        --query 'sort_by(Images, &CreationDate)[-1].ImageId' |
    jq \
        --compact-output \
        --raw-output \
        '. // empty'
}

function getInstanceAvailabilityZone()
{
    curl -s --retry 12 --retry-delay 5 'http://instance-data/latest/meta-data/placement/availability-zone'
}

function getInstanceID()
{
    curl -s --retry 12 --retry-delay 5 'http://instance-data/latest/meta-data/instance-id'
}

function getInstanceRegion()
{
    local -r availabilityZone="$(getInstanceAvailabilityZone)"

    checkNonEmptyString "${availabilityZone}" 'undefined availabilityZone'

    echo "${availabilityZone:0:${#availabilityZone} - 1}"
}

function getKeyPairFingerPrintByName()
{
    local -r keyPairName="${1}"

    checkNonEmptyString "${keyPairName}" 'undefined key pair name'

    aws ec2 describe-key-pairs \
        --key-name "${keyPairName}" 2> '/dev/null' |
    jq \
        --compact-output \
        --raw-output \
        '.["KeyPairs"] | .[0] | .["KeyFingerprint"] // empty'
}

function getSecurityGroupIDByName()
{
    local -r securityGroupName="${1}"

    checkNonEmptyString "${securityGroupName}" 'undefined security group name'

    aws ec2 describe-security-groups \
        --filters "Name=group-name,Values=${securityGroupName}" |
    jq \
        --compact-output \
        --raw-output \
        '.["SecurityGroups"] | .[0] | .["GroupId"] // empty'
}

function getSecurityGroupIDsByNames()
{
    local -r securityGroupNames=("${@}")

    local securityGroupID=''
    local securityGroupIDs=''
    local securityGroupName=''

    for securityGroupName in "${securityGroupNames[@]}"
    do
        securityGroupID="$(getSecurityGroupIDByName "${securityGroupName}")"

        checkNonEmptyString "${securityGroupID}" "security group name '${securityGroupName}' not found"

        securityGroupIDs="$(printf '%s\n%s' "${securityGroupIDs}" "${securityGroupID}")"
    done

    echo "${securityGroupIDs}"
}

function revokeSecurityGroupIngress()
{
    local -r securityGroupID="${1}"
    local -r securityGroupName="${2}"

    checkNonEmptyString "${securityGroupID}" 'undefined security group ID'
    checkNonEmptyString "${securityGroupName}" 'undefined security group name'

    local -r ipPermissions="$(
        aws ec2 describe-security-groups \
            --filters "Name=group-name,Values=${securityGroupName}" |
        jq \
            --compact-output \
            --raw-output \
            '.["SecurityGroups"] | .[0] | .["IpPermissions"] // empty'
    )"

    if [[ "$(isEmptyString "${ipPermissions}")" = 'false' && "${ipPermissions}" != '[]' ]]
    then
        aws ec2 revoke-security-group-ingress \
            --group-id "${securityGroupID}" \
            --ip-permissions "${ipPermissions}"
    fi
}

function updateInstanceName()
{
    local -r instanceName="${1}"

    header 'UPDATING INSTANCE NAME'

    checkNonEmptyString "${instanceName}" 'undefined instance name'

    info "${instanceName}"

    aws ec2 create-tags \
        --region "$(getInstanceRegion)" \
        --resources "$(getInstanceID)" \
        --tags "Key='Name',Value='${instanceName}'"
}

#####################
# GENERAL UTILITIES #
#####################

function checkValidRegion()
{
    local -r region="${1}"

    if [[ "$(isValidRegion "${region}")" = 'false' ]]
    then
        fatal "\nFATAL : invalid region '${region}'"
    fi
}

function getAllowedRegions()
{
    echo 'ap-northeast-1 ap-northeast-2 ap-south-1 ap-southeast-1 ap-southeast-2 ca-central-1 eu-central-1 eu-west-1 sa-east-1 us-east-1 us-east-2 us-west-1 us-west-2'
}

function getRegionFromRecordSetAliasTargetDNSName()
{
    local -r recordSetAliasTargetDNSName="${1}"

    # Regions

    local -r allowedRegions=($(getAllowedRegions))
    local region=''

    for region in "${allowedRegions[@]}"
    do
        if [[ "$(grep -F -i -o "${region}" <<< "${recordSetAliasTargetDNSName}")" != '' ]]
        then
            echo "${region}" && return 0
        fi
    done
}

function isValidRegion()
{
    local -r region="${1}"

    local -r allowedRegions=($(getAllowedRegions))

    isElementInArray "${region}" "${allowedRegions[@]}"
{'fraction_non_alphanumeric': 0.18167610861496386, 'fraction_numerical': 0.00966985739402227, 'mean_word_length': 2.9578662543486662, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '612179', 'n_tokens_mistral': 3162, 'n_tokens_neox': 3034, 'n_words': 635}