#!/usr/bin/python3
# Copyright 2023 Consolinno Energy GmbH
#
#    Licensed 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.

# Script which create a new openvpn client connection and activate it

import json
import os.path
import sys

if len(sys.argv) != 2:
    print("Must be invoked with exactly one argument: The JSON configuration.", file=sys.stderr)
    sys.exit(2)

config = sys.argv[1]

if not os.path.exists(config):
    print("Error: {} does not exist.".format(config), file=sys.stderr)
    sys.exit(1)

try:
    with open(config, "r") as configFile:
        data = json.load(configFile)
        #check if root element "openvpn-client" exists
        if "openvpn-client" in data:
            if "connection-name" in data["openvpn-client"] and "connection-config" in data["openvpn-client"]:
                # handle data
                print("connection-name: {}".format(data["openvpn-client"]["connection-name"]))
                # check if connection-name is a string and not empty
                if isinstance(data["openvpn-client"]["connection-name"], str) and data["openvpn-client"]["connection-name"]:
                    # print found connection-name
                    print("connection-name: {} found".format(data["openvpn-client"]["connection-name"]))
                    # set filename from connection-name in path /etc/openvpn/client
                    filename = "/etc/openvpn/client/{}.conf".format(data["openvpn-client"]["connection-name"])
                else:
                    print("connection-name is not a string or empty.")
                    sys.exit(0)
                # check if connection-config is a string and not empty
                if isinstance(data["openvpn-client"]["connection-config"], str) and data["openvpn-client"]["connection-config"]:
                    #print information about new openvpn client connection activation
                    print("connection-name: {} will be activated and enabled".format(data["openvpn-client"]["connection-name"]))
                    # write connection-config to file
                    with open(filename, "w") as f:
                        f.write(data["openvpn-client"]["connection-config"])
                    # activate openvpn-client service
                    os.system("systemctl enable openvpn-client@{}.service".format(data["openvpn-client"]["connection-name"]))
                    os.system("systemctl start openvpn-client@{}.service".format(data["openvpn-client"]["connection-name"]))
                    # return success
                    sys.exit(0)       
                else:
                    print("connection-config is not a string or empty. Disable and delete connection-name: {}".format(data["openvpn-client"]["connection-name"]))
                    # stop and deactivate openvpn-client service
                    os.system("systemctl stop openvpn-client@{}.service".format(data["openvpn-client"]["connection-name"]))
                    os.system("systemctl disable openvpn-client@{}.service".format(data["openvpn-client"]["connection-name"]))
                    #delete file if it exists
                    if os.path.exists(filename):
                        os.remove(filename)
                    sys.exit(0)
            else:
                print("No connection-name or connection-config found.")
                sys.exit(0)
        else:
            print("No openvpn-client configuration found.")
            sys.exit(0)
except Exception as e:
    print("Error: {}".format(e), file=sys.stderr)
    sys.exit(0)
