#!/bin/bash

last_dir=$(s3cmd ls s3://operations.backups.us-east-1/dev-system/ | grep DIR | tail -n1 | awk '{print $2}')
rm -fr tmp
mkdir -p tmp
s3cmd sync $last_dir tmp
cd tmp
echo 'gunzipping'
rm *HEX_DUMP*
gunzip *.sql.gz
echo 'gunzipped'
sed -i '/^INSERT INTO `\(log_entries\|cms_templates\|cms_files\|cms_sections\|cms_groups\|audits\|cms_templates_versions\|proxy_logs\)` VALUES/d' *data.sql
echo 'cms templates, files, groups, log entries, audits, proxy logs DELETED'
#perl -pi -e "if(/^INSERT INTO \`accounts\`/){ s/'(braintree_blue|stripe|ogone|authorize_net)','--- \!ruby\/hash:ActiveSupport::HashWithIndifferentAccess.*?\\\n'/'braintree_blue','--- \!ruby\/hash:ActionController::Parameters\ntest: \'1\'\npublic_key: baz\nmerchant_id: bar\nprivate_key: foo\n'/g }" *data.sql
#echo 'wiped all payment_gateways data'
sed -i "/^INSERT INTO \`users\`/s/'[a-z0-9]\{40\}','[a-z0-9]\{40\}'/'c944509aabc533481b629624f1b8c3fcab3fb189','b6cf550fa43984acafe24dfecd40b5d37818aa57'/g" *data.sql
echo 'all passwords are "p". ENJOY'
echo 'removing pg credentials'
perl -pi -e "if(/^INSERT INTO \`accounts\`/){ s/'(braintree_blue|stripe|ogone|authorize_net)','--- .*?[^\\\]',/'braintree_blue','--- \!ruby\/hash:ActionController::Parameters\\\ntest: \\\'1\\\'\\\npublic_key: baz\\\nmerchant_id: bar\\\nprivate_key: foo\\\n',/g }" data.sql
echo 'pg credentials REMOVED!'
echo 'gzipping now...'
cat *schema* *data* *triggers* >data.sql
gzip data.sql
echo "gziped in `pwd`/tmp."
echo ""
echo "STEPS to use it in your box:"
echo "download with 'scp jenkins@jenkins.3sca.net:`pwd`/data.sql.gz .'"
echo "unzip the file to db/data.sql"
echo "rake db:drop:all db:create:all db:data:load db:test:prepare"
echo "PROFIT!"
cd ..
