#!/usr/bin/python3 -tt
# - *- coding: utf- 8 - *-
#
#
# sapservices-move
#
# (c) 2020-2021 SUSE LLC
# Author: F.Herschel, L.Pinne
# GNU General Public License v2. No warranty.
# http://www.gnu.org/licenses/gpl.html
#

import os
import sys
import argparse
from pathlib import Path

__version__ = "2021-01-27 13:45"
SCRIPT_NAME = sys.argv[0]
SAPSERVICES = "/usr/sap/sapservices"

def do_stat():
    '''
    stat current sapservices file
    '''
    print(Path(SAPSERVICES).stat())

def do_cat():
    '''
    document current sapservices content
    '''
    with open(SAPSERVICES) as f:
        print(f.read())

def do_sanity_check():
    '''
    Check if the sapservices file exist
    '''
    if not os.path.isfile(SAPSERVICES):
        print('%s file does not exist' % SAPSERVICES)
        exit(1)

def do_hide():
    '''
    hide sapservices file by moving and creating an empty file
    '''
    do_sanity_check()
    do_stat()
    do_cat()
    #
    # only if sapservices is not already empty
    #
    if Path(SAPSERVICES).stat().st_size == 0:
        print("skip moving %s" % SAPSERVICES)
    else:
        #
        # touch empty file, move orig file, move-over empty file to hide
        #
        sapservices_empty = SAPSERVICES + ".empty"
        sapservices_moved = SAPSERVICES + ".moved"
        open(sapservices_empty, "w+").close()
        os.rename(SAPSERVICES, sapservices_moved)
        os.rename(sapservices_empty, SAPSERVICES)
        do_stat()

def do_unhide():
    '''
    unhide sapservices by restoring the previously hided version of the file
    '''
    do_sanity_check()
    do_stat()
    do_cat()
    if Path(SAPSERVICES).stat().st_size == 0:
        sapservices_moved = SAPSERVICES + ".moved"
        os.rename(sapservices_moved, SAPSERVICES)
    else:
        print("skip unhiding %s" % SAPSERVICES)
    do_stat()

def parse_arguments():
    '''
    Parse command line arguments
    '''
    parser = argparse.ArgumentParser(SCRIPT_NAME)

    parser.add_argument(
        '-v', '--version', help='Show script version', action="store_true")
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument(
        '--hide', help='Hide sapservices file', action="store_true")
    group.add_argument(
        '--unhide', help='Unhide sapservices file', action="store_true")

    args = parser.parse_args()
    return parser, args

def main():
    '''
    main method - take only exact ONE parameter
    '''
    parser, args = parse_arguments()
    if args.version:
        print("version: %s" % __version__)
    elif args.hide:
        do_hide()
    elif args.unhide:
        do_unhide()
    else:
        parser.print_help()

if __name__ == '__main__':  # pragma: no cover
    main()
