#!/bin/bash

# One-shot migration from the legacy single-file layout
# (configs/backup/backup_locations + configs/security/restic/loc_N.pass)
# to the per-location directory layout. Passwords now live as
# CFG_BACKUP_LOC_<idx>_PASSWORD inside the location.config — old .pass
# files get inlined and deleted.
#
# Idempotent — early-outs if the new layout is already present.

backupLocationsMigrate()
{
    local new_dir
    new_dir=$(backupLocationsDir)
    local old_file="$configs_dir/backup/backup_locations"

    # Already migrated? Detect by presence of at least one location.config.
    if [[ -d "$new_dir" ]]; then
        local existing
        existing=$(runFileOp find "$new_dir" -mindepth 2 -maxdepth 2 -name location.config -type f 2>/dev/null | head -1)
        if [[ -n "$existing" ]]; then
            return 0
        fi
    fi

    # Nothing to migrate AND no fresh seed in dev — skip silently.
    if [[ ! -f "$old_file" ]]; then
        return 0
    fi

    isHeader "Migrating backup locations to per-location directories"

    local owner
    owner=$(backupLocationOwner)
    runFileOp mkdir -p "$new_dir"
    runFileOp chown "$owner":"$owner" "$new_dir"
    runFileOp chmod 0755 "$new_dir"

    local indices
    indices=$(runFileOp grep -oE '^CFG_BACKUP_LOC_[0-9]+_' "$old_file" 2>/dev/null | grep -oE '[0-9]+' | sort -nu)
    if [[ -z "$indices" ]]; then
        isNotice "No locations found in legacy file — archiving without migration"
    fi

    local idx
    for idx in $indices; do
        local loc_dir cfg_file
        loc_dir=$(backupLocationDir "$idx")
        cfg_file=$(backupLocationConfig "$idx")

        runFileOp mkdir -p "$loc_dir"
        runFileOp chown "$owner":"$owner" "$loc_dir"
        runFileOp chmod 0700 "$loc_dir"

        local old_pass="${configs_dir}security/restic/loc_${idx}.pass"
        local pass_value=""
        if [[ -f "$old_pass" ]]; then
            pass_value=$(runFileOp cat "$old_pass" | tr -d '\n\r')
        fi
        [[ -z "$pass_value" ]] && pass_value="RANDOMIZEDPASSWORD1"

        {
            echo "# Backup location $idx — migrated $(date -Iseconds) from $old_file."
            echo "# Edit via the Locations page on /backup, or directly here."
            echo "CFG_BACKUP_LOC_${idx}_PASSWORD=${pass_value}                       # Repository Password - Used to encrypt/decrypt snapshots — back up offline!"
            runFileOp grep "^CFG_BACKUP_LOC_${idx}_" "$old_file" | grep -v "^CFG_BACKUP_LOC_${idx}_PASSWORD="
        } | runFileWrite "$cfg_file" >/dev/null
        runFileOp chown "$owner":"$owner" "$cfg_file"
        runFileOp chmod 0640 "$cfg_file"

        if [[ -f "$old_pass" ]]; then
            runFileOp rm -f "$old_pass"
            isNotice "Inlined password for location $idx into $cfg_file (old .pass removed)"
        elif declare -f replacePlainPasswords >/dev/null 2>&1; then
            replacePlainPasswords "$cfg_file"
        fi

        local old_kopia="${configs_dir}security/restic/kopia/loc_${idx}.config"
        local new_kopia
        new_kopia=$(backupLocationKopiaConfig "$idx")
        if [[ -f "$old_kopia" ]]; then
            runFileOp mv "$old_kopia" "$new_kopia"
            runFileOp chown "$owner":"$owner" "$new_kopia"
            runFileOp chmod 0600 "$new_kopia"
            isNotice "Moved kopia state for location $idx → $new_kopia"
        fi

        local old_ssh="${configs_dir}security/restic/ssh/loc_${idx}.key"
        local new_ssh
        new_ssh=$(backupLocationSshKey "$idx")
        if [[ -f "$old_ssh" ]]; then
            runFileOp mv "$old_ssh" "$new_ssh"
            runFileOp chown "$owner":"$owner" "$new_ssh"
            runFileOp chmod 0600 "$new_ssh"
            isNotice "Moved SSH key for location $idx → $new_ssh"
        fi

        isSuccessful "Location $idx migrated"
    done

    runFileOp mv "$old_file" "${old_file}.migrated"
    isSuccessful "Migration complete — old file archived as ${old_file}.migrated"

    # Re-source the new per-location configs so CFG vars reflect new state.
    sourceBackupLocations
}
