from hcloud import Client
import os
from hcloud.server_types.domain import ServerType
from hcloud.images.domain import Image
from hcloud.networks.domain import NetworkSubnet
from hcloud.locations.domain import Location
from hcloud.servers.domain import ServerCreatePublicNetwork


#region cloud inits
cloud_init_db=r'''#cloud-config

# lista podstawowych pakietów, które należy zainstalować
packages:
  - apt-transport-https
  - ca-certificates
  - curl
  - gnupg-agent
  - software-properties-common

# tworzymy plik docker-compose.yml
write_files:
  - path: /root/docker-compose.yml
    content: |
        version: '3.9'

        services:
          db:
              image: mysql:5.7
              restart: always
              ports:
                - "10.10.10.2:3306:3306"
              environment:
                MYSQL_ROOT_PASSWORD: "notSecureChangeMe"
                MYSQL_DATABASE: "gitea"
                MYSQL_USER: "gitea"
                MYSQL_PASSWORD: "gitea"
              volumes:
                - db_data:/var/lib/mysql
        volumes:
          db_data: {}

# instalujemy docker i docker-compose, a następnie uruchamiamy naszą bazę danych
runcmd:
  - curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
  - add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
  - apt-get update -y
  - apt-get install -y docker-ce docker-ce-cli containerd.io
  - curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
  - chmod +x /usr/local/bin/docker-compose
  - systemctl start docker
  - systemctl enable docker
  - cd /root/ && docker-compose up -d
'''

cloud_init_gitea=r'''#cloud-config

# lista podstawowych pakietów, które należy zainstalować
packages:
  - apt-transport-https
  - ca-certificates
  - curl
  - gnupg-agent
  - software-properties-common

# tworzymy plik docker-compose.yml
write_files:
  - path: /root/docker-compose.yml
    content: |
        version: "3.9"

        services:
          server:
            image: gitea/gitea:1.21.3
            environment:
                USER_UID: "1000"
                USER_GID: "1000"
                GITEA__database__DB_TYPE: "mysql"
                GITEA__database__HOST: "10.10.10.2:3306"
                GITEA__database__NAME: "gitea"
                GITEA__database__USER: "gitea"
                GITEA__database__PASSWD: "gitea"
            restart: always
            volumes:
              - ./gitea:/data
              - /etc/timezone:/etc/timezone:ro
              - /etc/localtime:/etc/localtime:ro
            ports:
              - "3000:3000"

# instalujemy docker, docker-compose a następnie uruchamiamy nasz serwer
runcmd:
  - curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
  - add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
  - apt-get update -y
  - apt-get install -y docker-ce docker-ce-cli containerd.io
  - curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
  - chmod +x /usr/local/bin/docker-compose
  - systemctl start docker
  - systemctl enable docker
  - cd /root/ && docker-compose up -d
'''

#endregion

PREFIX = "s486867"

def create_ssh_key(client):
    return client.ssh_keys.create(name=f"{PREFIX}-pzc-ssh-key", public_key=os.environ['PUBLIC_KEY'])

def create_network(client):
    vnet_name = f"{PREFIX}-pzc-test-vnet"
    subnet = NetworkSubnet(ip_range="10.10.10.0/24", network_zone="eu-central", type="cloud")
    return client.networks.create(name=vnet_name, ip_range="10.10.10.0/24", subnets=[subnet])

def create_server(client, name, user_data):
    server_type = ServerType("cx11")
    image = Image(name="ubuntu-20.04")
    ssh_key = create_ssh_key(client)
    network = create_network(client)
    location = Location("hel1")
    return client.servers.create(name=name, server_type=server_type, image=image, ssh_keys=[ssh_key], networks=[network], location=location, user_data=user_data)

def wait_until_server_finished(server):
    server.action.wait_until_finished()
    return server.action.complete

def get_server_public_ip(server):
    server = client.servers.get_by_name(server.name)
    return server.data_model.public_net.ipv4.ip

if __name__ == "__main__":
    client = Client(token=os.environ['HETZNER_TOKEN'])

    cloud_init_db = "<cloud_init_db_content>"
    cloud_init_gitea = "<cloud_init_gitea_content>"

    db_server = create_server(client, f"{PREFIX}-db", cloud_init_db)
    print(f"Tworzenie serwera db: {wait_until_server_finished(db_server)}")

    gitea_server = create_server(client, f"{PREFIX}-gitea-1", cloud_init_gitea)
    print(f"Tworzenie serwera gitea-1: {wait_until_server_finished(gitea_server)}")

    print(f"Publiczny adres IP: {get_server_public_ip(gitea_server)}")