#!/usr/bin/env python3

import argparse
import json

import requests


PROJECT = {
    "environments": [
      {
        "env": "{}",
        "json": "{}",
        "name": "Empty"
      }
    ],
    "integration_aliases": [],
    "integrations": [],
    "inventories": [
      {
        "inventory": "/opt/semaphore/repo/fuss-playbooks/hosts",
        "name": "local GLPI",
        "ssh_key": "fuss_server_root",
        "type": "file"
      }
    ],
    "keys": [
      {
        "name": "fuss_server_root",
        "owner": "",
        "type": "ssh"
      },
      {
        "name": "None",
        "owner": "",
        "type": "none"
      }
    ],
    "meta": {
      "alert": False,
      "max_parallel_tasks": 0,
      "name": "FUSS",
      "type": ""
    },
    "repositories": [
      {
        "git_branch": "",
        "git_url": "/opt/semaphore/repo/fuss-playbooks/",
        "name": "FUSS Playbooks",
        "ssh_key": "None"
      }
    ],
    "roles": [],
    "schedules": [],
    "secret_storages": [],
    "templates": [],
    "views": [
      {
        "hidden": False,
        "position": 0,
        "sort_reverse": False,
        "title": "All",
        "type": "all"
      }
    ]
}


class SemaphoreClient:

    def __init__(self):
        self.parse_args()
        self.ca_cert = f"/etc/ssl/certs/{self.args.domain}-cacert.pem"

    def parse_args(self):
        parser = argparse.ArgumentParser()
        parser.add_argument(
            "semaphore_url",
        )
        parser.add_argument(
            "-p", "--password",
        )
        parser.add_argument(
            "-u", "--user",
            default="admin"
        )
        parser.add_argument(
            "-d", "--domain",
        )

        self.args = parser.parse_args()

    def get_token(self):
        self.headers = {
            "Content-Type": "application/json",
            "accept": "application/json",
        }

        with requests.Session() as s:
            payload = {
                "auth": self.args.user,
                "password": self.args.password,
            }
            r = s.post(
                f"{self.args.semaphore_url}/api/auth/login",
                data=json.dumps(payload),
                verify=self.ca_cert,
                headers=self.headers,
                )

            r = s.post(
                f"{self.args.semaphore_url}/api/user/tokens",
                verify=self.ca_cert,
                headers=self.headers,
            )
            token = json.loads(r.content)["id"]
        self.headers["Authorization"] = f"Bearer {token}"

    def import_project(self):
        self.get_token()
        r = requests.get(
            f"{self.args.semaphore_url}/api/projects",
            verify=self.ca_cert,
            headers=self.headers,
            )
        for p in json.loads(r.content):
            if p["name"] == "FUSS":
                print("A project named FUSS already exists, exiting")
                return

        r = requests.post(
            f"{self.args.semaphore_url}/api/projects/restore",
            verify=self.ca_cert,
            headers=self.headers,
            data=json.dumps(PROJECT)
        )

        if r.status_code != 200:
            print("Could not create project:", r.status_code, r.reason)
            return
        else:
            pr_id = json.loads(r.content)["id"]
            print(f"Project id {pr_id} created")

        r = requests.get(
            f"{self.args.semaphore_url}/api//project/{pr_id}/keys",
            verify=self.ca_cert,
            headers=self.headers,
        )
        keys = json.loads(r.content)

        key_id = None
        for key in keys:
            if key["name"] == "fuss_server_root":
                key_id = key["id"]
                break

        with open("/root/.ssh/id_ed25519") as fp:
            secret = fp.read()

        new_key = {
            "id": key_id,
            "name": "fuss_server_root",
            "type": "ssh",
            "project_id": pr_id,
            "override_secret": True,
            "login_password": {
                "password": "",
                "login": "",
            },
            "ssh": {
                "login": "root",
                "passphrase": "",
                "private_key": secret,
            },
        }

        r = requests.put(
            f"{self.args.semaphore_url}/api/project/{pr_id}/keys/{key_id}",
            verify=self.ca_cert,
            headers=self.headers,
            data=json.dumps(new_key)
        )

        if r.status_code != 204:
            print("Could not update key:", r.status_code, r.reason)
            return
        else:
            print(f"Key id {key_id} loaded")


if __name__ == "__main__":
    SemaphoreClient().import_project()
