File: //proc/29734/root/newvolume/exchange.sh
#!/bin/bash
# Configuration
CSV="testingexchange.csv"
OUTPUT="mapping_local_only.csv"
# Initialize CSV Header
echo "trade_id,original_invoice_path,original_po_path,new_invoice_path,new_po_path" > "$OUTPUT"
echo "Starting process..."
# We use process substitution to keep stdin clean
# We also use sed to strip carriage returns and skip the header
while IFS=',' read -r trade_id invoice_document_path purchase_order_document_path
do
# --- 1. Data Cleaning ---
# Strip \r and trim whitespace
tid=$(echo "$trade_id" | tr -d '\r' | xargs)
inv_raw=$(echo "$invoice_document_path" | tr -d '\r' | xargs)
po_raw=$(echo "$purchase_order_document_path" | tr -d '\r' | xargs)
# Skip empty rows (like the ones in your test file)
if [[ -z "$tid" || -z "$inv_raw" ]]; then
continue
fi
echo "------------------------------------------"
echo "Processing Trade ID: $tid"
# --- 2. Path Correction ---
# Convert "/documents/..." to "documents/..." (Relative path)
local_inv="${inv_raw#/}"
local_po="${po_raw#/}"
process_file() {
local filepath="$1"
local tid="$2"
local type="$3" # "invoice" or "po"
if [[ -f "$filepath" ]]; then
dir=$(dirname "$filepath")
ext="${filepath##*.}"
base=$(basename "$filepath")
# Replace part after _invoice_ or _po_ with trade_id
new_filename=$(echo "$base" | sed -E "s/(_${type}_).*\.${ext}$/\1${tid}.${ext}/")
new_filepath="$dir/$new_filename"
if [[ "$filepath" == "$new_filepath" ]]; then
echo "ALREADY_RENAMED:$new_filepath"
else
mv "$filepath" "$new_filepath"
echo "SUCCESS:$new_filepath"
fi
else
echo "ERROR:FILE_NOT_FOUND:$filepath"
fi
}
# --- 3. Execute Renaming ---
# Process Invoice
inv_result=$(process_file "$local_inv" "$tid" "invoice")
if [[ $inv_result == SUCCESS:* || $inv_result == ALREADY_RENAMED:* ]]; then
new_inv_path="${inv_result#*:}"
echo " [Inv] Renamed to: $new_inv_path"
else
new_inv_path="FILE_NOT_FOUND"
echo " [Inv] $inv_result"
fi
# Process PO
po_result=$(process_file "$local_po" "$tid" "po")
if [[ $po_result == SUCCESS:* || $po_result == ALREADY_RENAMED:* ]]; then
new_po_path="${po_result#*:}"
echo " [PO] Renamed to: $new_po_path"
else
new_po_path="FILE_NOT_FOUND"
echo " [PO] $po_result"
fi
# --- 4. Log to CSV ---
echo "$tid,$inv_raw,$po_raw,$new_inv_path,$new_po_path" >> "$OUTPUT"
done < <(tail -n +2 "$CSV")
echo "------------------------------------------"
echo "Process finished. Check '$OUTPUT' for the summary."
echo "Uploading documents folder to Azure Blob..."
STORAGE_ACCOUNT="credebtmachine"
SAS_TOKEN="si=exchange&spr=https&sv=2024-11-04&sr=c&sig=lfXsQkYc0uG3LU40QcaiczMcgsm0nL%2Bty1SY7mUz640%3D"
azcopy copy "documents" \
"https://${STORAGE_ACCOUNT}.blob.core.windows.net/exchange?${SAS_TOKEN}" \
--recursive
if [[ $? -eq 0 ]]; then
echo "Upload successful."
# If you want MOVE behavior (delete local after upload):
# rm -rf documents
else
echo "Upload failed!"
exit 1
fi