#!/bin/sh
# These functions are embedded in the new package's preupgrade and postupgrade.
umask 077
INSTALL_DIR="${SYNOPKG_PKGDEST:-/var/packages/nastunnel/target}"

upgrade_storage() {
    store="${SYNOPKG_PKGVAR:-/var/packages/nastunnel/var}"
    if [ ! -d "$store" ] || [ ! -w "$store" ]; then
        store="${SYNOPKG_TEMP_UPGRADE_FOLDER:-}"
    fi
    case "$store" in /*) ;; *) return 1 ;; esac
    [ -d "$store" ] && [ -w "$store" ] || return 1
    resolved=$(readlink -f "$store") || return 1
    app=$(readlink -f "$INSTALL_DIR") || return 1
    case "$resolved" in "$app"|"$app"/*) return 1 ;; esac
    SNAPSHOT="$resolved/.nastunnel-upgrade-state-v2"
}

owned_directory() (
    source=$1
    destination=$2
    [ -d "$source" ] && [ ! -L "$source" ] || return 1
    [ ! -L "$destination" ] || return 1
    mkdir -p "$destination" || return 1
    mode=$(stat -c '%a' "$source") || return 1
    expected_owner=$(stat -c '%u:%g' "$source") || return 1
    owner=$(stat -c '%u:%g' "$destination") || return 1
    if [ "$owner" != "$expected_owner" ]; then
        chown "$expected_owner" "$destination" || return 1
    fi
    chmod "$mode" "$destination"
)

copy_persistent_file() (
    source=$1
    destination=$2
    [ ! -L "$source" ] && [ ! -L "$destination" ] || exit 1
    if [ ! -e "$source" ]; then exit 0; fi
    [ -f "$source" ] || exit 1
    if [ -e "$destination" ] && [ ! -f "$destination" ]; then exit 1; fi
    tmp=$(mktemp "$(dirname "$destination")/.nastunnel-state.XXXXXXXX") || exit 1
    trap 'rm -f "$tmp"' EXIT
    cp -p "$source" "$tmp" && mv -f "$tmp" "$destination"
)

copy_device_certificates() (
    source=$1
    destination=$2
    [ ! -L "$source" ] || exit 1
    if [ ! -e "$source" ]; then exit 0; fi
    owned_directory "$source" "$destination" || exit 1
    for host_dir in "$source"/*; do
        if [ ! -e "$host_dir" ] && [ ! -L "$host_dir" ]; then continue; fi
        domain=${host_dir##*/}
        case "$domain" in *[!a-z0-9.-]*|.*|*.) continue ;; *.*) ;; *) continue ;; esac
        [ ! -L "$host_dir" ] || exit 1
        [ -d "$host_dir" ] || continue
        new_host="$destination/$domain"
        owned_directory "$host_dir" "$new_host" || exit 1
        for name in active.json pending.json enrollment-denied.json; do
            copy_persistent_file "$host_dir/$name" "$new_host/$name" || exit 1
        done
    done
)

# Only these two package-owned trees are copied. Configured NAS folders and
# library symlinks remain references to their original locations.
same_share_entry() (
    first=$1 second=$2
    [ "$(stat -c '%f:%u:%g' "$first")" = "$(stat -c '%f:%u:%g' "$second")" ] || exit 1
    if [ -L "$first" ]; then
        [ -L "$second" ] && [ "$(readlink "$first")" = "$(readlink "$second")" ]
        exit $?
    fi
    [ ! -L "$second" ] || exit 1
    if [ -f "$first" ]; then
        [ -f "$second" ] && cmp -s "$first" "$second"
        exit $?
    fi
    [ -d "$first" ] && [ -d "$second" ] || exit 1
    for child in "$first"/* "$first"/.[!.]* "$first"/..?*; do
        if [ -e "$child" ] || [ -L "$child" ]; then
            same_share_entry "$child" "$second/${child##*/}" || exit 1
        fi
    done
    for child in "$second"/* "$second"/.[!.]* "$second"/..?*; do
        if [ -e "$child" ] || [ -L "$child" ]; then
            [ -e "$first/${child##*/}" ] || [ -L "$first/${child##*/}" ] || exit 1
        fi
    done
)

copy_share_tree() (
    source_dir=$1 target_dir=$2
    [ ! -L "$source_dir" ] && [ ! -L "$target_dir" ] || exit 1
    [ -e "$source_dir" ] || exit 0
    [ -d "$source_dir" ] || exit 1
    parent=$(dirname "$target_dir")
    [ -d "$parent" ] && [ ! -L "$parent" ] || exit 1
    # A filesystem mounted under the package is managed separately. Stop before
    # enumerating it instead of copying a mounted NAS volume into the package.
    real_source=$(readlink -f "$source_dir") || exit 1
    if [ -r /proc/self/mountinfo ]; then
        awk -v root="$real_source" '$5==root || index($5,root "/")==1 { found=1 } END {exit found?1:0}' /proc/self/mountinfo || exit 1
    fi
    # Archive regular files, directories and link objects; never open devices or pipes.
    special=$(find "$source_dir" ! -type f ! -type d ! -type l -print) || exit 1
    [ -z "$special" ] || exit 1
    if [ -e "$target_dir" ]; then
        [ -d "$target_dir" ] || exit 1
        if same_share_entry "$source_dir" "$target_dir"; then exit 0; fi
        # The new package may already have created an empty placeholder. Keep
        # any conflicting nonempty tree intact so a retry cannot discard data.
        rmdir "$target_dir" 2>/dev/null || exit 1
    fi
    stage_dir=$(mktemp -d "$parent/.nastunnel-share-state.XXXXXXXX") || exit 1
    trap 'if [ -d "$stage_dir" ]; then rm -rf "$stage_dir"; fi' EXIT
    cp -a "$source_dir" "$stage_dir/tree" || exit 1
    same_share_entry "$source_dir" "$stage_dir/tree" || exit 1
    [ ! -e "$target_dir" ] && [ ! -L "$target_dir" ] || exit 1
    mv -T "$stage_dir/tree" "$target_dir" || exit 1
)


copy_selected_state() (
    source=$1
    destination=$2
    for area in conf var; do
        [ ! -L "$source/$area" ] && [ ! -L "$destination/$area" ] || exit 1
        if [ -d "$source/$area" ]; then owned_directory "$source/$area" "$destination/$area" || exit 1; fi
    done
    copy_persistent_file "$source/conf/config.json" "$destination/conf/config.json" || exit 1
    for shared_area in file-share share-files; do
        copy_share_tree "$source/var/$shared_area" "$destination/var/$shared_area" || exit 1
    done
    copy_persistent_file "$source/var/private-network.json" "$destination/var/private-network.json" || exit 1
    old_mesh="$source/var/private-network"
    new_mesh="$destination/var/private-network"
    [ ! -L "$old_mesh" ] && [ ! -L "$new_mesh" ] || exit 1
    if [ -e "$old_mesh" ]; then
        owned_directory "$old_mesh" "$new_mesh" || exit 1
        for mesh_profile in "$old_mesh"/*; do
            if [ ! -e "$mesh_profile" ] && [ ! -L "$mesh_profile" ]; then continue; fi
            profile_name=${mesh_profile##*/}
            case "$profile_name" in *[!0-9-]*|*-*-*|-*|*-) continue ;; *-*) ;; *) continue ;; esac
            [ ! -L "$mesh_profile" ] || exit 1
            [ -d "$mesh_profile" ] || continue
            owned_directory "$mesh_profile" "$new_mesh/$profile_name" || exit 1
            copy_persistent_file "$mesh_profile/identity" "$new_mesh/$profile_name/identity" || exit 1
        done
    fi
    for name in native-https.json webrtc-device.json p2p-observation-enabled auto_start_disabled last_servers last_vkey; do
        copy_persistent_file "$source/var/$name" "$destination/var/$name" || exit 1
    done

    old_state="$source/var/native-https-state"
    new_state="$destination/var/native-https-state"
    [ ! -L "$old_state" ] || exit 1
    if [ -e "$old_state" ]; then
        owned_directory "$old_state" "$new_state" || exit 1
        for device_dir in "$old_state"/*; do
            if [ ! -e "$device_dir" ] && [ ! -L "$device_dir" ]; then continue; fi
            device=${device_dir##*/}
            case "$device" in ''|*[!0-9]*) continue ;; esac
            copy_device_certificates "$device_dir" "$new_state/$device" || exit 1
        done
    fi

    # The earlier single-device pilot installed only these named components.
    old_pilot="$source/var/native-https-pilot"
    new_pilot="$destination/var/native-https-pilot"
    copy_device_certificates "$old_pilot" "$new_pilot" || exit 1
    for name in gateway issued-chain.pem; do
        copy_persistent_file "$old_pilot/$name" "$new_pilot/$name" || exit 1
    done
)

snapshot_complete() {
    [ -d "$SNAPSHOT" ] && [ ! -L "$SNAPSHOT" ] && [ -f "$SNAPSHOT/.complete" ] && [ ! -L "$SNAPSHOT/.complete" ]
}
set -eu
upgrade_storage || { printf '%s\n' 'NAS Tunnel could not allocate a private upgrade backup.' >&2; exit 1; }
if [ -e "$SNAPSHOT" ] || [ -L "$SNAPSHOT" ]; then
    snapshot_complete || exit 1
    exit 0
fi
stage=$(mktemp -d "$resolved/.nastunnel-upgrade-stage.XXXXXXXX")
trap 'if [ -d "$stage" ]; then rm -rf "$stage"; fi' EXIT
copy_selected_state "$INSTALL_DIR" "$stage" || { printf '%s\n' 'NAS Tunnel could not back up device settings.' >&2; exit 1; }
touch "$stage/.complete"
mv "$stage" "$SNAPSHOT"
exit 0
