#!/usr/bin/python3

"""
    workspace++

    ws_restore

    python version of ws_restore command, only for root

    restores expired workspaces 
    Reads new YAML configuration files and new YAML workspace database.

    (c) Holger Berger 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024

    workspace++ is based on workspace by Holger Berger, Thomas Beisel and Martin Hecht

    workspace++ 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.

    workspace++ 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 workspace++.  If not, see <http://www.gnu.org/licenses/>.

"""


from __future__ import print_function
import yaml
import os, os.path, sys


if os.getuid() != 0:
    print("Error: you are not root.", file=sys.stderr)
    sys.exit(-1)

# load config file
config = yaml.safe_load(open("/etc/ws.conf"))

if len(sys.argv) == 1:
    print("Usage: ws_restore <workspace>", file=sys.stderr)
    sys.exit(0)

workspaceid = sys.argv[1]

for fs in config["workspaces"]:
    dbdeldir = os.path.join(config["workspaces"][fs]["database"], config["workspaces"][fs]["deleted"])
    dbdir = config["workspaces"][fs]["database"]
    dbentry = os.path.join(dbdeldir, workspaceid)
    if os.path.exists(dbentry):
        if os.path.exists(os.path.join(dbdir, workspaceid[: workspaceid.rfind("-")])):
            print("Error: workspace with same name %s exists, resolve it by hand!", file=sys.stderr)
            sys.exit(-1)
        else:
            entry = yaml.safe_load(open(dbentry))
            try:
                wsentry = os.path.join(
                    os.path.dirname(entry["workspace"]), config["workspaces"][fs]["deleted"], workspaceid
                )
            except TypeError:
                f = open(dbentry)
                expiration = int(f.readline())
                wsentry = os.path.join(
                    os.path.dirname(f.readline()[:-1]), config["workspaces"][fs]["deleted"], workspaceid
                )
                f.close()
            if os.path.exists(wsentry):
                os.rename(dbentry, os.path.join(dbdir, workspaceid[: workspaceid.rfind("-")]))
                os.rename(wsentry, entry["workspace"])
                print("Info: workspace found and restored", file=sys.stderr)
                exit(0)
            else:
                print("Error: workspace not found!", file=sys.stderr)
                exit(-1)

print("Error: workspace not found", file=sys.stderr)
