#!/bin/bash

if [ "$DEBUG" = 'true' ]
then
   set -x
fi

HERE=`pwd`

script_dir="$(dirname "$0")"
cd $script_dir

source df.config || true

download(){
    resp=$(curl -s --fail -k $MANTA_URL"data_functions/$DATA_FUNCTION_ID/download_link?api_key=$API_KEY" -H "Content-Type: application/json")
    link_status=$?
    if [ $link_status -eq 0 ]
    then
        echo "Successfully fetched download link"
    else
        echo "Could not retrieve a download link"
        exit $link_status
    fi

    url=$(echo $resp | jq .Code.Location | tr -d '"')
    curl -s "$url" -o "downloaded_"$DATA_FUNCTION_ID".zip"
    download_status=$?
    if [ $download_status -eq 0 ]
    then
        echo "Downloaded most recently deployed code to downloaded_"$DATA_FUNCTION_ID".zip"
    else
        echo "Could not download the zip"
        exit $download_status
    fi
}

deploy() {
    set -e
    # Zip everything in the current directory of the data function and below into a zip file
    zip -r ./function.zip ./* &> "${HERE}/debug.log"
    DATA_FUNCTION_ZIP="./function.zip"
    POST_DATA='{"id":"'$DATA_FUNCTION_ID'", "api_key": "'$API_KEY'"}'

    presigned_resp=$(curl --fail -s -k -X POST -d "$POST_DATA" $MANTA_URL"data_functions/deploy_url" -H "Content-Type: application/json")
    presigned_exit_code=$?
    if [ $presigned_exit_code != 0 ]; then
        echo "Couldn't get upload url"
        exit 1
    fi

    url=$(echo $presigned_resp | jq .presigned_url | tr -d '"')
    no_https=${url#https://}
    BUCKET=${no_https%%.s3*}
    no_query=${no_https%%\?*}
    KEY=${no_query##*s3.amazonaws.com/}

    ### upload to the presigned URL
    curl -s --upload-file $DATA_FUNCTION_ZIP $url
    s3_upload_result=$?
    #    echo "S3 upload result $s3_upload_result"

    sp="/-\|"
    j=0
    n=${#sp}
    for i in `seq 1 180`;
    do
        BIG_STR=""
        ((j++))
        SPIN_CHAR="${sp:j%n:1}"
        EXIT_STATUS=0
        resp=$(curl -s -k $MANTA_URL"data_functions/$DATA_FUNCTION_ID/poll_for_complete?api_key=$API_KEY&bucket=$BUCKET&key=$KEY" -H "Content-Type: application/json")
#        echo "$resp"
        complete=$(echo "$resp" | jq .complete)
        success=$(echo "$resp" | jq .success)
        if [ "$success" = "true" ]; then
            BIG_STR=$BIG_STR"Deploy was successful"
            echo
            echo "$BIG_STR"
            exit 0
        fi

        if [ "$complete" = "true" ]; then
            BIG_STR=$BIG_STR"Deploy is complete but it was not successful"
            echo
            echo "$BIG_STR"
            exit 1
        fi

        if [ "$complete" = "false" ]; then
            BIG_STR=$BIG_STR"Deploy is not yet finished "
            BIG_STR=$SPIN_CHAR" $BIG_STR "$SPIN_CHAR
            echo -ne "\r $BIG_STR "
            sleep 1
        fi
    done
    echo
}



help(){
    HELP=$(cat <<-EOF

./data-function [help|deploy|call_channel] [args]...

            help:  Show this help message
    call_channel:  Call the channel associated with this DF and display the result
          deploy:  Deploys the data function from the users local machine to the cloud.
                       After deploy is complete the data function is available to associated channels
        download:  Downloads the current deploy of the data function

EOF
        )
    echo "$HELP"
}

call_channel(){
    ./examples/call_channel.sh
}

attach(){
    resp=$(curl -s --fail -k $MANTA_URL"data_functions/pipes.json?api_key=$API_KEY" -H "Content-Type: application/json")
    pipe_list_status=$?
    if [ $pipe_list_status -eq 0 ]
    then
        echo $resp | jq
        read -p "Which Pipe would you like to associate this data function ($DF_NAME) with? (Enter id) " read_pipe_id
        ASSOCIATE_TO_PIPE_DATA='{"pipe_id": '$read_pipe_id', "data_function_id": '$DATA_FUNCTION_ID', "api_key": "'$API_KEY'"}'
        read -p "Associate data function $DF_NAME to pipe $read_pipe_id ? (y/n) " confirm
        case "$confirm" in
            [Yy]* )
                echo "Will do boss"
                ;;
            [Nn]* )
                echo "Doing nothing"
                exit 1
                ;;
            * )
                echo "Please answer yes or no."
                exit 1
                ;;
        esac
        ATTACH_OUT=/tmp/attach.out
        rm $ATTACH_OUT
        RESP=$(curl -s -w '%{http_code}' -o $ATTACH_OUT -k -d "$ASSOCIATE_TO_PIPE_DATA" $MANTA_URL"data_functions/add_data_function_to_pipe" -H "Content-Type: application/json")
        pwd
        if [ "$RESP" = "200" ]
        then
            echo "Successfully associated $DF_NAME to pipe $read_pipe_id "
        else
            echo "Failed to associated $DF_NAME to pipe $read_pipe_id "
            cat $ATTACH_OUT
        fi

    else
        echo "Could not retrieve pipes"
        echo $resp
        exit $pipes_list_status
    fi
}

tail_logs(){
    cred_url=$MANTA_URL"data_functions/"$DATA_FUNCTION_ID"/tail_log_credentials?api_key=$API_KEY"
    echo "Cred URL "$cred_url
    scram=$(curl -k "$cred_url")

    echo "$scram"

    export AWS_ACCESS_KEY_ID=$(echo "$scram" | jq .access_key_id | tr -d '"')
    export AWS_SECRET_ACCESS_KEY=$(echo "$scram" | jq .secret_access_key | tr -d '"')
    export AWS_SESSION_TOKEN=$(echo "$scram" | jq .session_token | tr -d '"')

    echo 'export AWS_ACCESS_KEY_ID='$AWS_ACCESS_KEY_ID
    echo 'export AWS_SECRET_ACCESS_KEY='$AWS_SECRET_ACCESS_KEY
    echo 'export AWS_SESSION_TOKEN='$AWS_SESSION_TOKEN

    echo "After assume-role"
    aws sts get-caller-identity

#    now=$(date +%s)
#    minutes=5
#    minutes_ago=$(( $minutes * 60 ))
#    now_minutes_ago=$(( ($now - $minutes_ago) * 1000 ))
#    echo "now - "$minutes" minutes ago as js milliseconds unix epoch" $now_minutes_ago
#    logs=$(aws logs filter-log-events --log-group-name="/aws/lambda/$DATA_FUNCTION_NAME" --interleaved --start-time=$now_minutes_ago 2>&1)

    awslogs get "/aws/lambda/$DATA_FUNCTION_NAME" ALL --watch

    echo $?
    echo 'Logs '$logs
    echo "ALL DONE"
}

update_sdk(){
    # hit manta for updated data-function file and updated function/demyst_helper.py
    cli_url=$MANTA_URL"data_functions/cli_file?api_key=$API_KEY"
    new_cli_file=$(curl --fail -k "$cli_url")
    if [ $? = 0 ]; then
        mv "$script_dir/data-function" "$script_dir/data-function.bak"
        echo "$new_cli_file" > $script_dir"/data-function"
        chmod 755 $script_dir"/data-function"
        rm "$script_dir/data-function.bak"
    else
        echo "Attempt to pull new cli file failed"
        exit 1
    fi

    helper_url=$MANTA_URL"data_functions/helper_file?api_key=$API_KEY"
    new_helper_file=$(curl --fail -k "$helper_url")
    if [ $? = 0 ]; then
        mv $script_dir"/function/demyst_helper.py" $script_dir"/function/demyst_helper.py.bak"
        echo "$new_helper_file" > $script_dir"/function/demyst_helper.py"
        rm $script_dir"/function/demyst_helper.py.bak"
    else
        echo "Attempt to pull new helper file failed"
        exit 1
    fi

}

case "$1" in
    "deploy")
        deploy
        ;;
    "help")
        help
        ;;
    "call_channel")
        call_channel
        ;;
    "download")
        download
        ;;
    "attach")
        attach
        ;;
    "tail_logs")
        tail_logs
        ;;
    "update_sdk")
        update_sdk
        ;;
    *)
        echo "./cli/data-function-ctl deploy|help|call_channel|download|attach|tail_logs|update_sdk"
        exit 1
        ;;
esac
