#
#  This file is part of Synoindex Watcher.
#
#  Copyright (c) 2012-2018 Mark Houghton <https://codesourcery.wordpress.com>
#  Copyright (c) 2019-2020 Torben Haase <https://pixelsvsbytes.com>
#
#  Synoindex Watcher is free software: you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the Free
#  Software Foundation, either version 3 of the License, or (at your option) any
#  later version.
#
#  Synoindex Watcher is distributed in the hope that it will be useful, but
#  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
#  details. You should have received a copy of the GNU General Public License
#  along with Synoindex Watcher. If not, see <https://www.gnu.org/licenses/>.
#
################################################################################

import sys

def generateConfig(args):
    blacklist = args.blacklist if args.blacklist else ""
    whitelist = args.whitelist if args.whitelist else ""
    logfile = args.logfile if args.logfile else ""
    content = """[GLOBAL]
blacklist=%s
whitelist=%s
logfile=%s
loglevel=%s""" % (blacklist, whitelist, logfile, args.loglevel)
    for path in args.path:
        content += "\n\n[%s]" % path
    return content

def generateInit(argv):
    args = argv[1:]
    try: args.remove("--rebuild-index")
    except ValueError: pass
    try: args.remove("--generate-init")
    except ValueError: pass
    try: args.remove("--generate-config")
    except ValueError: pass
    try: args.remove("--help")
    except ValueError: pass
    args = " ".join(args)
    return """#!/bin/sh

# This file has been generated by Synoindex Watcher.

ARGS="%s"
PIDFILE="/var/run/synoindexwatcher.pid"

start_synoindexwatcher() {
    if [ ! -f "$PIDFILE" ]; then
        echo "Starting synoindexwatcher..."
        # Set LC_ALL to ensure that the filesystem encoding is correctly
        # detected during boot.
        nohup env LC_ALL=en_US.utf8 %s -m synoindexwatcher $ARGS > /dev/null 2>&1 &
        echo $! > "$PIDFILE"
    else
        echo "Error: synoindexwatcher has already been started"
        exit 1
    fi
}

stop_synoindexwatcher() {
    if [ -f "$PIDFILE" ]; then
        echo "Stopping synoindexwatcher..."
        kill `cat "$PIDFILE"`
        rm "$PIDFILE"
    else
        echo "Error: synoindexwatcher has not been started yet"
        exit 1
    fi
}

case "$1" in
    start|"")
        start_synoindexwatcher
        ;;
    restart|reload|force-reload)
        stop_synoindexwatcher
        start_synoindexwatcher
        ;;
    stop)
        stop_synoindexwatcher
        ;;
    *)
        echo "Usage: `basename $0` [start|stop]" >&2
        exit 3
        ;;
esac""" % (args, sys.executable)
