#!/bin/bash
[ "$1" == "" ] && exec echo "Usage: $0 [--log-dir <path>] <TABLE_NAME>"

source $HOME/.gamerc

SCRIPT_NAME=$(basename "$0")
LOCK_FILE="/tmp/.${SCRIPT_NAME}.lock"

exec 200>"${LOCK_FILE}"
flock -n 200 || {
        echo "${SCRIPT_NAME} is running. Exiting."
    exit 1
}

# ── 選項解析 ──────────────────────────────────────────────────────────────────
FILES_DIR=""
while [[ "${1:-}" == --* ]]; do
    case "$1" in
        --log-dir) FILES_DIR="$(dirname "$2")"; shift 2 ;;
        *) shift ;;
    esac
done

TABLE_NAME=$1
if [[ -z "$FILES_DIR" ]]; then
    FILES_DIR="${HOME}/www/tools/files"
fi
WORK_DIR="${FILES_DIR}/itemmall_web"

get_table_primay_key_orders () {
    TABLE_NAME=$1
    RETURN=$(psql -U postgres ${GAME_TYPE}Account -c "
           COPY (SELECT a.attnum  AS column_number FROM pg_index i
            JOIN pg_class t ON t.oid = i.indrelid
            JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(i.indkey)
            WHERE
            i.indisprimary AND t.relname = '${TABLE_NAME}' AND pg_catalog.pg_table_is_visible(t.oid)) TO STDOUT;")
    echo ${RETURN}
}

rm -rf ${WORK_DIR}/${TABLE_NAME}.diff*;

mkdir -p ${WORK_DIR}/test/; cd ${WORK_DIR}/test; echo "Dump ${TABLE_NAME} on TEST ..."; pg_dump -U postgres ${GAME_TYPE}Account -t ${TABLE_NAME} | sed '/^\\unrestrict /d' | sed '/^\\restrict /d' | sed '/^$/d' | sort > ${TABLE_NAME}_testbackup_new_current.sql

ssh ACCOUNTDB "echo 'Dump ${TABLE_NAME} on LIVE ...'; pg_dump -U postgres ${GAME_TYPE}Account -t ${TABLE_NAME} | sed '/^\\\\unrestrict /d' | sed '/^\\\\restrict /d' | sed '/^$/d' | sort > /tmp/${TABLE_NAME}_livebackup_old_current.sql"
mkdir -p ${WORK_DIR}/live/; cd ${WORK_DIR}/live; rsync -avz ACCOUNTDB:/tmp/${TABLE_NAME}_livebackup_old_current.sql . >/dev/null 2>&1

cd ${WORK_DIR}
pkey_search=$(get_table_primay_key_orders ${TABLE_NAME})
echo ${pkey_search}

input_file="${TABLE_NAME}.diff.content"
pkey_file="${TABLE_NAME}.diff.pkey"
modify_file="${TABLE_NAME}.diff.content.modify"
new_file="${TABLE_NAME}.diff.content.new"
delete_file="${TABLE_NAME}.diff.content.delete"
output_file="${TABLE_NAME}.diff.output"

diff test/${TABLE_NAME}_testbackup_new_current.sql live/${TABLE_NAME}_livebackup_old_current.sql | grep -E -a -v 'Dump' | grep -E -a '<|>' | grep -v "GRANT ALL ON TABLE public.${TABLE_NAME} TO PUBLIC;" > ${input_file}
cat ${input_file}

# Build dynamic key and print expressions
key_expr=""
out_expr=""
for col in $pkey_search; do
    key_expr="$key_expr\$${col} FS "
    out_expr="$out_expr\$${col} OFS "
done
# Remove trailing FS / OFS
key_expr="${key_expr% FS }"
out_expr="${out_expr% OFS }"

# === Step 1: Extract unique pkeys ===
awk -v key_expr="$key_expr" -v print_expr="$print_expr" -v cols="$pkey_search" '
function make_key(fields, cols,    i, idx, key) {
    split(cols, idx, " ")
    key = ""
    for (i = 1; i <= length(idx); i++) {
        key = key (i > 1 ? FS : "") fields[idx[i]]
    }
    return key
}
{
    sub(/^[><] /, "", $0)
    split($0, fields, /[ \t]+/)
    key = make_key(fields, cols)
    if (!(key in seen)) {
        seen[key] = 1
        print key
    }
}
' "$input_file" | sort -nk1,1 > "$pkey_file"
cat ${pkey_file}

echo "====== Modify ======" >> ${modify_file}
echo "====== New ======" >> ${new_file}
echo "====== Delete ======" >> ${delete_file}

# === Step 2: Process each key ===
if [ -s "${pkey_file}" ]; then
    while IFS= read -r key; do
        awk -v key="$key" -v cols="$pkey_search" '
        function match_key(fields, key, cols,    i, idx, val, cmp) {
            split(cols, idx, " ")
            split(key, val, " ")
            for (i = 1; i <= length(idx); i++) {
                if (fields[idx[i]] != val[i])
                    return 0
            }
            return 1
        }
        {
            line = $0
            sub(/^[><] /, "", line)
            split(line, fields, /[ \t]+/)

            if (match_key(fields, key, cols)) {
                if ($0 ~ /^</) before = $0
                if ($0 ~ /^>/) after = $0
            }
        }
        END {
            if (before && after) {
                print key >> "'"$modify_file"'"
                print after >> "'"$modify_file"'"
                print before >> "'"$modify_file"'"
            } else if (before) {
                print key >> "'"$new_file"'"
                print before >> "'"$new_file"'"
            } else if (after) {
                print key >> "'"$delete_file"'"
                print after >> "'"$delete_file"'"
            }
        }
        ' "$input_file"
    done < "$pkey_file"
fi

[ -f "${output_file}" ] && rm -rf ${output_file}
echo >> ${output_file}
cat ${new_file} >> ${output_file}
echo >> ${output_file}
cat ${modify_file} >> ${output_file}
echo >> ${output_file}
cat ${delete_file} >> ${output_file}

cat ${output_file}

[ -f "${LOCK_FILE}" ] && rm -f ${LOCK_FILE}
