#!/bin/bash

# Base directory where projects live
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REMOTE="root@172.237.116.126"
LOG_FILE="$DIR/deploy.log"

# 1. Gather projects
mapfile -t projects < <(find "$DIR" -maxdepth 1 -mindepth 1 -type d -printf "%f\n" | sort)

if [ ${#projects[@]} -eq 0 ]; then
    echo "No projects found in $DIR"
    exit 1
fi

# 2. Select Project
echo "Select a project to push to prod:"
for i in "${!projects[@]}"; do
    idx=$((i+1))
    echo " $idx) ${projects[i]}"
done

read -p "Enter number of project to push: " sel
if ! [[ "$sel" =~ ^[0-9]+$ ]] || (( sel < 1 || sel > ${#projects[@]} )); then
    echo "Invalid selection."; exit 1
fi

choice="${projects[sel-1]}"

# 3. Path Logic
source="$DIR/$choice/"
dest_path="/var/www/html/$choice"

dest="$REMOTE:$dest_path"

# 4. Pre-flight Checks
if [ -z "$(ls -A "$source")" ]; then
    echo "ERROR: Source directory '$source' is empty! Deployment aborted."
    exit 1
fi

# Check remote disk space
DISK_CHECK=$(ssh "$REMOTE" "df -h /var/www/html | tail -1 | awk '{print \$4}'")
echo "Remote disk space available: $DISK_CHECK"

# 5. Backup (Remote Snapshot)
echo "Creating remote backup of $dest_path..."
ssh "$REMOTE" "tar -czf ${dest_path}_backup_$(date +%Y%m%d_%H%M%S).tar.gz -C $(dirname "$dest_path") $(basename "$dest_path") 2>/dev/null || echo 'No existing files to backup.'"

# 6. Dry-Run
echo "---"
echo "Project: $choice"
echo "Source:  $source"
echo "Dest:    $dest"
echo "---"
echo "Performing dry-run..."
rsync -avz --include='.*' --dry-run "$source" "$dest"
echo "---"

# 7. Workflow Decision
read -p "Does the list above look correct? (y/N/wipe): " confirm

if [[ "$confirm" =~ ^(y|yes)$ ]]; then
    echo "Syncing files..."
    rsync -avz --delete --include='.*' "$source" "$dest"
    
elif [[ "$confirm" =~ ^(w|wipe)$ ]]; then
    echo "WARNING: Hard wiping remote directory $dest_path..."
    ssh "$REMOTE" "rm -rf $dest_path && mkdir -p $dest_path"
    echo "Copying fresh files via SCP..."
    # Note: scp -r with source/* copies all contents, including hidden files
    scp -r "$source"/.* "$source"/* "$REMOTE":"$dest_path"
else
    echo "Push cancelled."
    exit 0
fi

# 8. Post-Sync: Permissions & Verification
echo "Fixing permissions (www-data)..."
ssh "$REMOTE" "chown -R www-data:www-data $dest_path && \
               find $dest_path -type d -exec chmod 777 {} \; && \
               find $dest_path -type f -exec chmod 777 {} \;"

# 9. File Count Verification
LOCAL_COUNT=$(find "$source" -type f | wc -l)
REMOTE_COUNT=$(ssh "$REMOTE" "find $dest_path -type f | wc -l")

if [ "$LOCAL_COUNT" -eq "$REMOTE_COUNT" ]; then
    echo "Success: Sync confirmed ($LOCAL_COUNT files)."
    echo "[$(date)] Pushed '$choice' to $dest_path" >> "$LOG_FILE"
else
    echo "WARNING: Local count ($LOCAL_COUNT) does not match remote count ($REMOTE_COUNT)!"
fi
