#!/usr/bin/bash

set -e

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

# Lock file to prevent overlapping cron runs
LOCKFILE="/tmp/SyncNRLogFileToS3.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"
}

# -------------------------------------------------------------------
# Operator input
# -------------------------------------------------------------------
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

# Convert to lowercase
OPERATOR="${OPERATOR,,}"

# -------------------------------------------------------------------
# INPUT
# -------------------------------------------------------------------
BASE_DIR="/opt/device/P20_logs/"
MINUTES=15

# Option 1: auto-detect device IDs
AUTO_DETECT_DEVICES=true

# Option 2: manually configure device IDs
MANUAL_DEVICE_IDS=("csblrlabsvtcc9ec132-1132" "csblrlabsvtcc9ec132-1132-test")


ACCOUNT_ID=$(/usr/bin/aws sts get-caller-identity --query "Account" --output text)
REGION="ap-southeast-1"
BUCKET="${ACCOUNT_ID}-${REGION}-onecell-files"

# -------------------------------------------------------------------
# Determine device IDs
# -------------------------------------------------------------------
DEVICE_IDS=()
if [ "$AUTO_DETECT_DEVICES" = true ]; then
    log "Auto-detecting device IDs under $BASE_DIR/$OPERATOR"
    while IFS= read -r dir; do
        DEVICE_IDS+=("$(basename "$dir")")
    done < <(find "$BASE_DIR/$OPERATOR" -mindepth 1 -maxdepth 1 -type d 2>/dev/null)
else
    DEVICE_IDS=("${MANUAL_DEVICE_IDS[@]}")
    log "Using manually configured device IDs: ${DEVICE_IDS[*]}"
fi

log "Script Started"
log "Account ID: $ACCOUNT_ID"
log "Region:     $REGION"
log "S3 bucket:  $BUCKET"

# -------------------------------------------------------------------
# Iterate over devices
# -------------------------------------------------------------------
for DEV in "${DEVICE_IDS[@]}"; do
    FILES_PATH="$BASE_DIR/$OPERATOR/$DEV/"

    if [ ! -d "$FILES_PATH" ]; then
        log "WARNING: files directory does not exist: $FILES_PATH\n"
        continue
    fi
	
	log "\n"
	log "-------------------------------------------"
    log "Scanning device directory: $FILES_PATH\n"

    # Fetch ONLY files directly under files/ (no subfolders)
    FILES=$(find "$FILES_PATH" -maxdepth 1 -type f -mmin -"$MINUTES" 2>/dev/null || true)

    if [ -z "$FILES" ]; then
        log "No files found in $FILES_PATH updated in last $MINUTES minutes"
        continue
    fi

    for FILE in $FILES; do
        BASENAME=$(basename "$FILE")

        DATE=$(echo "$BASENAME" | grep -oE '[0-9]{8}' | head -n1)
        if [ -z "$DATE" ]; then
            log "Skipping file (no date found): $FILE"
            continue
        fi

        DEST="s3://$BUCKET/onecell/$OPERATOR/NR/logs/$DATE/"
        log "Copying: $FILE → $DEST"

        if /usr/bin/aws s3 cp "$FILE" "$DEST"; 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"
            #fi
        else
            log "ERROR: Failed to copy file to S3: $FILE"
        fi
    done
	log "-------------------------------------------"
done

log "\n"
log "-------------------------------------------"
log "All eligible NR files processed successfully."
log "Script Execution Completed"

