#!/usr/bin/bash

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
LOG_FILE="$SCRIPT_DIR/log/LTE_OMFileToS3_$(date '+%Y%m%d_%H%M%S').log"

# Lock file to prevent overlapping cron runs
LOCKFILE="/tmp/SyncLTEOMFileToS3.lock"
exec 200>$LOCKFILE
flock -n 200 || {
    echo "$(date '+%Y-%m-%d %H:%M:%S')  Another instance is running. Exiting." >> "$LOG_FILE"
    exit 1
}

# -------------------------------------------------------------------
log() {
    echo -e "$(date '+%Y-%m-%d %H:%M:%S')  $1" | tee -a "$LOG_FILE"
}

if [ $# -ne 1 ]; then
    echo "Usage: $0 <operator>"
    exit 1
fi

OPERATOR=$1

if [[ ! "$OPERATOR" =~ ^[a-z]{3}$ && ! "$OPERATOR" =~ ^[A-Z]{3}$ ]]; then
    echo "ERROR: Operator Name must be 3 letters, either all small or all caps."
    echo "Examples: att, ATT"
    exit 1
fi

# Converting to lowercase for internal processing
OPERATOR="${OPERATOR,,}"

###########################################
#INPUTS
###########################################
BASE_DIR="/opt/device/logs/onecell/0005B9"       # Base directory to scan
MINUTES=15                                  	 # Lookback window
ACCOUNT_ID=$(/usr/bin/aws sts get-caller-identity --query "Account" --output text)
#REGION=$(/usr/local/bin/aws configure get region)
REGION=ap-south-1
###########################################

BUCKET=$ACCOUNT_ID-${REGION}-onecell-files  #s3 bucket name

log "Script Started"
echo "Account ID: $ACCOUNT_ID" | tee -a $LOG_FILE
echo "Region:     $REGION"     | tee -a $LOG_FILE
echo -e "S3 bucket:  $BUCKET\n"   | tee -a $LOG_FILE

log "Scanning directory: $BASE_DIR"
log "Finding PM files updated in last $MINUTES minutes..."

FILES=$(find "$BASE_DIR" -type f -name "*PERFORMANCE*" -mmin -"$MINUTES")

if [ -z "$FILES" ]; then
    log "No PM files updated in the last $MINUTES minutes."
    exit 0
fi

for FILE in $FILES; do

    BASENAME=$(basename "$FILE")

    # Extract 14-digit timestamp
    TIMESTAMP=$(echo "$BASENAME" | grep -oE '[0-9]{14}')

    if [ -z "$TIMESTAMP" ]; then
        log "Skipping file (no timestamp found): $FILE"
        continue
    fi

    # Extract YYYYMMDD from timestamp
    DATE=${TIMESTAMP:0:8}

    DEST="s3://$BUCKET/onecell/$OPERATOR/LTE/PM/$DATE/"
    log "Copying: $FILE → $DEST\n"

    /usr/bin/aws s3 cp "$FILE" "$DEST"

    if [ $? -eq 0 ]; then
       log "File copied successfully: $FILE"

       #log "Deleting $FILE"
       #if rm -f "$FILE"; then
       #   log "File deleted: $FILE"
       #else
       #   log "WARNING: Unable to delete file: $FILE"
       #   log "Skipping deletion and continuing..."
       #fi
    else
       log "ERROR: Failed to copy file to S3: $FILE"
    fi

log "===========================================\n"

done

log "All eligible LTE PM files moved successfully."

