#!/usr/bin/env bash
# Installs a package from tools/release/build-assets.sh into a Nuhet app directory, or rolls
# one back (#3598). See docs/ops/asset-release.md for the full procedure.
#
# Usage:
#   install-assets.sh --app DIR --package nuhet-assets-<short>.tar.gz [options]
#   install-assets.sh --app DIR --rollback BACKUP_DIR [options]
#
#   --app DIR             the Laravel root (the directory with public/ and .git), e.g. /var/www/html
#   --package FILE        the tarball; FILE.sha256 from the build must sit next to it
#   --rollback DIR        put back the files saved in DIR by an earlier install
#   --owner USER:GROUP    owner for written files (default: the owner of DIR/public)
#   --backup-root DIR     where backups go (default: $HOME/nuhet-asset-backups)
#   --allow-other-commit  install although the package was built from another commit than
#                         the app's git HEAD (normally a mistake)
#   --dry-run             check everything and print the plan, change nothing
#
# Every file is written next to its target and renamed into place, so a request sees the
# old file or the new one, never half a file. mix-manifest.json is switched last. Before
# anything changes, the script checks that it can write every folder it needs and saves the
# current version of every affected file under --backup-root/<time>-<commit>/. The command to
# undo the install is printed at the end, or as soon as the switch fails part way.
# DIR/asset-release.json records what the last install or rollback put in place.
set -euo pipefail
umask 022

die() { echo "install-assets: $*" >&2; exit 2; }

self="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")"
app=
package=
rollback=
owner=
backup_root="${HOME:-/root}/nuhet-asset-backups"
allow_other_commit=0
dry_run=0
while [ $# -gt 0 ]; do
    case "$1" in
        --app) app=${2:?--app needs a directory}; shift 2 ;;
        --package) package=${2:?--package needs a file}; shift 2 ;;
        --rollback) rollback=${2:?--rollback needs a directory}; shift 2 ;;
        --owner) owner=${2:?--owner needs USER:GROUP}; shift 2 ;;
        --backup-root) backup_root=${2:?--backup-root needs a directory}; shift 2 ;;
        --allow-other-commit) allow_other_commit=1; shift ;;
        --dry-run) dry_run=1; shift ;;
        -h|--help) sed -n '2,23p' "$0"; exit 0 ;;
        *) die "unknown argument: $1 (see --help)" ;;
    esac
done

[ -n "$app" ] || die "--app is required"
[ -d "$app/public" ] || die "$app has no public/ directory"
app=$(cd "$app" && pwd)
# The checkout usually belongs to the deploy user; under sudo git would refuse it as "dubious".
app_git() { git -c safe.directory="$app" -C "$app" "$@"; }
if [ -n "$package" ] && [ -n "$rollback" ]; then die "use --package or --rollback, not both"; fi
if [ -z "$package" ] && [ -z "$rollback" ]; then die "--package or --rollback is required"; fi
for tool in tar gzip sha256sum stat cmp; do command -v "$tool" >/dev/null || die "$tool is not installed"; done

owner_option=()
if [ -n "$owner" ]; then owner_option=(--owner "$owner"); else owner=$(stat -c '%U:%G' "$app/public"); fi
[[ "$owner" == *:* ]] || die "--owner must be USER:GROUP"
case "$backup_root" in /*) ;; *) backup_root="$PWD/$backup_root" ;; esac
me="$(id -un):$(id -gn)"
is_root=0
[ "$(id -u)" = 0 ] && is_root=1
if [ "$is_root" = 0 ] && [ "$owner" != "$me" ]; then
    die "files must belong to $owner but this runs as $me; run it as root (sudo) or as that user"
fi

work=$(mktemp -d "${TMPDIR:-/tmp}/nuhet-assets-install-XXXXXX")
switching=0
undo=
pending=
on_exit() {
    local status=$?
    rm -rf "$work"
    if [ -n "$pending" ]; then rm -f "$pending"; fi
    if [ "$switching" = 1 ] && [ "$status" != 0 ]; then
        echo "install-assets: stopped part way (exit $status); $app may now mix old and new files." >&2
        echo "install-assets: put the previous files back with:" >&2
        echo "  $undo" >&2
    fi
}
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM HUP

# Paths must be plain relative paths under public/.
check_path() {
    case "$1" in
        public/*) ;;
        *) die "refusing a path outside public/: $1" ;;
    esac
    case "/$1/" in
        */../*|*/./*|*//*) die "refusing an unsafe path: $1" ;;
    esac
}

# --- What to write (source dir + SHA256SUMS) and what to delete -----------------------------
deletes=()
if [ -n "$package" ]; then
    [ -f "$package" ] || die "no such package: $package"
    [ -f "$package.sha256" ] || die "missing $package.sha256 (copy it with the tarball)"
    (cd "$(dirname "$package")" && sha256sum -c --quiet "$(basename "$package").sha256") \
        || die "the tarball does not match its .sha256; copy it again"
    top=$(tar -tzf "$package" | cut -d/ -f1 | sort -u)
    [[ "$top" =~ ^nuhet-assets-[0-9a-f]{8}$ ]] || die "not a build-assets tarball (top level: $top)"
    while IFS= read -r member; do
        case "/$member/" in */../*) die "refusing tarball member $member" ;; esac
    done < <(tar -tzf "$package")
    tar -xzf "$package" -C "$work" --no-same-owner --no-same-permissions
    source_dir="$work/$top"
    [ -z "$(find "$source_dir" ! -type f ! -type d -print -quit)" ] || die "the tarball contains links or special files"
    commit=$(grep -oE '"commit": "[0-9a-f]{40}"' "$source_dir/release-assets.json" | grep -oE '[0-9a-f]{40}') \
        || die "release-assets.json has no commit"
    label="${commit:0:8}"
    sums="$source_dir/SHA256SUMS"
else
    if [ ! -d "$rollback/files" ] || [ ! -f "$rollback/SHA256SUMS" ] || [ ! -f "$rollback/ABSENT" ]; then
        die "$rollback is not a backup made by this script"
    fi
    rollback=$(cd "$rollback" && pwd)
    source_dir="$rollback/files"
    sums="$rollback/SHA256SUMS"
    while IFS= read -r path; do
        [ -n "$path" ] || continue
        check_path "$path"
        deletes+=("$path")
    done < "$rollback/ABSENT"
    commit=
    label="rollback-$(basename "$rollback")"
fi

writes=()
while IFS= read -r line; do
    [ -n "$line" ] || continue
    path=${line#*  }
    check_path "$path"
    writes+=("$path")
done < "$sums"
# A backup of a first install has no files, so its SHA256SUMS is empty.
if [ -s "$sums" ]; then
    (cd "$source_dir" && sha256sum -c --quiet "$sums") || die "files do not match their checksums"
fi
[ "${#writes[@]}" -gt 0 ] || [ "${#deletes[@]}" -gt 0 ] || die "nothing to install"

# --- The package must belong to the deployed commit ----------------------------------------
if [ -n "$commit" ]; then
    head=$(app_git rev-parse HEAD 2>/dev/null) || head=
    if [ "$head" != "$commit" ]; then
        if [ "$allow_other_commit" = 1 ]; then
            echo "WARNING: package is for $commit, app HEAD is ${head:-unknown}; installing anyway." >&2
        else
            die "package is for $commit but $app is at ${head:-an unknown commit (git rev-parse HEAD failed in $app)}; deploy that commit first or pass --allow-other-commit"
        fi
    fi
fi

# --- Can every folder be written? Checked before anything changes, also in a dry run --------
marker="$app/asset-release.json"
declare -A unwritable=()
need_dir_for() {
    # $1 is a path that will be created or replaced; its nearest existing folder must be writable.
    local dir
    dir=$(dirname "$1")
    while [ ! -e "$dir" ] && [ ! -L "$dir" ]; do dir=$(dirname "$dir"); done
    [ -d "$dir" ] || die "$dir is in the way: it is not a folder"
    if [ ! -w "$dir" ] || [ ! -x "$dir" ]; then unwritable["$dir"]=1; fi
}
for path in "${writes[@]}"; do
    if [ -e "$app/$path" ] && [ ! -f "$app/$path" ]; then die "$app/$path exists but is not a regular file"; fi
    need_dir_for "$app/$path"
done
for path in "${deletes[@]}"; do
    if [ -e "$app/$path" ] && [ ! -f "$app/$path" ]; then die "$app/$path exists but is not a regular file"; fi
    if [ -e "$app/$path" ]; then need_dir_for "$app/$path"; fi
done
need_dir_for "$marker"
need_dir_for "$backup_root/x"
if [ "${#unwritable[@]}" -gt 0 ]; then
    {
        echo "install-assets: $me cannot write to:"
        printf '  %s\n' "${!unwritable[@]}" | sort
        echo "install-assets: nothing was changed. Run it as root (sudo), or fix the owner of those folders first."
    } >&2
    exit 2
fi

# --- Plan ----------------------------------------------------------------------------------
new=0 changed=0 same=0
for path in "${writes[@]}"; do
    if [ ! -e "$app/$path" ]; then new=$((new + 1))
    elif cmp -s "$source_dir/$path" "$app/$path"; then same=$((same + 1))
    else changed=$((changed + 1)); fi
done
echo "$label into $app as $owner: ${#writes[@]} files ($changed changed, $new new, $same unchanged), ${#deletes[@]} to remove."
if [ "$dry_run" = 1 ]; then
    for path in "${writes[@]}"; do
        if [ ! -e "$app/$path" ]; then echo "  new      $path"
        elif ! cmp -s "$source_dir/$path" "$app/$path"; then echo "  changed  $path"; fi
    done
    for path in "${deletes[@]}"; do echo "  remove   $path"; done
    echo "Dry run: nothing changed."
    exit 0
fi

# --- Backup of everything this will touch --------------------------------------------------
backup="$backup_root/$(date -u +%Y%m%dT%H%M%SZ)-$label"
[ -e "$backup" ] && die "$backup already exists"
mkdir -p "$backup/files"
: > "$backup/ABSENT"
: > "$backup/SHA256SUMS"
for path in "${writes[@]}" "${deletes[@]}"; do
    if [ -f "$app/$path" ]; then
        mkdir -p "$backup/files/$(dirname "$path")"
        cp -p "$app/$path" "$backup/files/$path"
        (cd "$backup/files" && sha256sum "$path") >> "$backup/SHA256SUMS"
    else
        echo "$path" >> "$backup/ABSENT"
    fi
done
{
    echo "app=$app"
    echo "installed=$label"
    echo "owner=$owner"
    echo "app_head=$(app_git rev-parse HEAD 2>/dev/null || echo unknown)"
    echo "time=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
} > "$backup/INFO"
# Keeps a record on the server of which build was installed.
if [ -n "$package" ]; then cp "$source_dir/release-assets.json" "$backup/installed-release-assets.json"; fi
# The record of what was in place before, so a rollback can say what it brings back.
if [ -f "$marker" ]; then cp "$marker" "$backup/previous-asset-release.json"; fi
if [ -s "$backup/SHA256SUMS" ]; then
    (cd "$backup/files" && sha256sum -c --quiet ../SHA256SUMS) || die "backup check failed; nothing was changed"
fi
echo "Backup: $backup"
undo=$(printf '%q ' "$self" --app "$app" --rollback "$backup" --backup-root "$backup_root" ${owner_option[@]+"${owner_option[@]}"})
undo=${undo% }

# --- Switch files: everything else first, mix-manifest.json last ---------------------------
# Writes $2 (a file) to $1 the atomic way, creating missing folders with the right owner.
place() {
    local target=$1 from=$2 dir tmp d created=()
    dir=$(dirname "$target")
    d=$dir
    while [ ! -d "$d" ]; do created+=("$d"); d=$(dirname "$d"); done
    if [ "${#created[@]}" -gt 0 ]; then
        mkdir -p "$dir"
        if [ "$is_root" = 1 ]; then chown "$owner" "${created[@]}"; fi
    fi
    tmp="$dir/.$(basename "$target").nuhet-new.$$"
    pending=$tmp
    cp "$from" "$tmp"
    chmod 0644 "$tmp"
    if [ "$is_root" = 1 ]; then chown "$owner" "$tmp"; fi
    mv -f "$tmp" "$target"
    pending=
}
put() { place "$app/$1" "$source_dir/$1"; }
switching=1
manifest=public/mix-manifest.json
for path in "${writes[@]}"; do [ "$path" = "$manifest" ] || put "$path"; done
for path in "${writes[@]}"; do [ "$path" != "$manifest" ] || put "$path"; done
for path in "${deletes[@]}"; do [ "$path" = "$manifest" ] || rm -f "$app/$path"; done
for path in "${deletes[@]}"; do [ "$path" != "$manifest" ] || rm -f "$app/$path"; done

# --- Verify --------------------------------------------------------------------------------
(cd "$source_dir" && while IFS= read -r line; do
    [ -n "$line" ] || continue
    path=${line#*  }
    [ "$(sha256sum < "$app/$path" | cut -d' ' -f1)" = "${line%%  *}" ] || { echo "install-assets: $app/$path does not match after install" >&2; exit 3; }
done < "$sums")
for path in "${deletes[@]}"; do [ ! -e "$app/$path" ] || die "$app/$path is still there"; done

# --- Record what is in place now: DIR/asset-release.json (outside public/, not served) -------
json() { local s=$1; s=${s//\\/\\\\}; s=${s//\"/\\\"}; printf '"%s"' "$s"; }
by=$(id -un)
if [ -n "${SUDO_USER:-}" ]; then by="$by (sudo from $SUDO_USER)"; fi
if [ -n "$package" ]; then
    action=install
    live_commit=$(json "$commit")
    details="    \"package\": $(json "$(basename "$package")"),
    \"package_sha256\": $(json "$(cut -d' ' -f1 "$package.sha256")"),"
else
    action=rollback
    # The commit recorded before the install that is undone; null if nothing was recorded then.
    previous=$(grep -oE '"commit": "[0-9a-f]{40}"' "$rollback/previous-asset-release.json" 2>/dev/null | head -n 1 | grep -oE '[0-9a-f]{40}') || previous=
    if [ -n "$previous" ]; then live_commit=$(json "$previous"); else live_commit=null; fi
    undone=$(sed -n 's/^installed=//p' "$rollback/INFO" 2>/dev/null | head -n 1) || undone=
    details="    \"undid\": $(json "${undone:-unknown}"),
    \"restored_from\": $(json "$rollback"),"
fi
cat > "$work/asset-release.json" <<EOF
{
    "action": "$action",
    "commit": $live_commit,
$details
    "time": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "by": $(json "$by"),
    "backup": $(json "$backup"),
    "undo": $(json "$undo")
}
EOF
place "$marker" "$work/asset-release.json"
switching=0

echo "Installed $label (recorded in $marker). To undo:"
echo "  $undo"
