#!/usr/bin/env bash

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# For each filespec FS given (one per line) on stdin, rename FS (if it exists) to FS.old, then rename FS.new to
# FS.

if [[ "$*" = "--help" ]] ; then
    echo "For each filespec FS read from stdin, rename FS.new to FS. If FS already exists, rename to FS.old" >&2
    exit 0
fi

while read F
do
python3 - "$F" << THE_END

import sys
import os

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def rename_file(old_path, new_path):
    try:
        os.rename(old_path, new_path)
    except:
        eprint(f"fatal error: failure renaming {old_path} to {new_path}\n")
        sys.exit(1)

def rename_to_old(pathspec):
    op = pathspec + ".old"

    if os.access(op, os.F_OK):
        last = 2
        while os.access(op + ".{}".format(last), os.F_OK):
            last += 1
        while last > 2:
            rename_file(op + ".{}".format(last - 1), op + ".{}".format(last))
            last -= 1
        rename_file(op, op + ".2")

    rename_file(pathspec, op)

filespec = sys.argv[1]
if os.access(filespec, os.F_OK):
    rename_to_old(filespec)
rename_file(filespec + ".new", filespec)

sys.exit(0)

THE_END
done
