#!/bin/bash

function log_message() {
  # $1 message to be logged
  echo >&2 "`date -u "+%F %H:%M"` | $1"
}

function copy_credentials() {
  cp vehicle/perception/cas/analyzer/credentials ~/.aws/
  cp vehicle/perception/cas/analyzer/.pgpass ~/
  chmod 0600 ~/.pgpass
  log_message "copy_credentials() is done"
}

function rs_prep_schema() {
: '
  Runs create table screipts, which make sure that staging table in the redshift
  exist before tha data is being copied to them.
'
  local RS_USER="yxie"
  local PATH_TO_RS_CREATE_TABLE_SCRIPTS="vehicle/perception/cas/analyzer"

  # Add Schema for Events
  psql -h 'redshift-db01.c1iujdhow47v.us-west-1.redshift.amazonaws.com' \
      -U $RS_USER \
      -d 'temp_db' \
      -p '5439' \
      -c "`cat $PATH_TO_RS_CREATE_TABLE_SCRIPTS/safety_pcp_rs_events.sql`"

  # Add Schema for Runs
  psql -h 'redshift-db01.c1iujdhow47v.us-west-1.redshift.amazonaws.com' \
      -U $RS_USER \
      -d 'temp_db' \
      -p '5439' \
      -c "`cat $PATH_TO_RS_CREATE_TABLE_SCRIPTS/safety_pcp_rs_runs.sql`"

  log_message "rs_prep_schema() is done"
}

function rs_upload_data() {

  local RS_USER="yxie"

  # Import Events
  psql -h 'redshift-db01.c1iujdhow47v.us-west-1.redshift.amazonaws.com' \
      -U $RS_USER \
      -d 'temp_db' \
      -p '5439' \
      -c "COPY dbt_yxie.safety_pcp_debug_e_events
          from 's3://redshiftdb01/safety_pcp/To_RS/events'
          credentials 'aws_access_key_id=AKIAIJ7JSCSM75HCAGAQ;aws_secret_access_key=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'
          NULL AS 'NULL' CSV IGNOREHEADER 1;"

  aws s3 rm s3://redshiftdb01/safety_pcp/To_RS/events/ --recursive --exclude "*" --include "*.csv"

  log_message "events operations are done"

  # Import Runs
  psql -h 'redshift-db01.c1iujdhow47v.us-west-1.redshift.amazonaws.com' \
      -U $RS_USER \
      -d 'temp_db' \
      -p '5439' \
      -c "COPY dbt_yxie.safety_pcp_debug_runs
          from 's3://redshiftdb01/safety_pcp/To_RS/runs'
          credentials 'aws_access_key_id=AKIAIJ7JSCSM75HCAGAQ;aws_secret_access_key=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'
          NULL AS 'NULL' CSV IGNOREHEADER 1;"

  aws s3 rm s3://redshiftdb01/safety_pcp/To_RS/runs --recursive --exclude "*" --include "*.csv"

  log_message "runs operations are done"
}

# Copy AWS credential.
copy_credentials

# Run the preparation stage.
rs_prep_schema

# Run the uploading process.
rs_upload_data

