import subprocess
import requests
import datetime
now = datetime.datetime.now()
DATETIME = now.strftime("%Y%m%d%H%M%S")
print("Backup gitlab")
cmnd = 'docker exec -t gitlab gitlab-backup create SKIP=artifacts,repositories,registry,uploads,builds,pages,lfs,packages,terraform_state'
status, output = subprocess.getstatusoutput(cmnd)
print("Backup nextcloud")
cmnd = 'docker exec --user www-data nextcloud-app-1 php occ maintenance:mode --on'
status, output = subprocess.getstatusoutput(cmnd)
cmnd = f"docker exec nextcloud-db-1 sh -c 'exec mysqldump --single-transaction -h localhost -u nextcloud -pl4c1j4yd33Du5lo nextcloud' > /share/docker_data/__backups/nextcloudDB_{DATETIME}.sql"
status, output = subprocess.getstatusoutput(cmnd)
cmnd = "docker exec --user www-data nextcloud-app-1 php occ maintenance:mode --off"
status, output = subprocess.getstatusoutput(cmnd)

print("Backup portainer")
headers = {
    'Content-Type': 'application/json; charset=utf-8',
    'x-api-key':'ptr_gfwpbP4AUDhZ4uoPmSfNUGqZq+gescoele8reP/l/GU=',
}

json_data = {
    'password': 'l4c1j4yd33Du5lo',
}

response = requests.post('https://portainer.sectorq.eu/api/backup', headers=headers, json=json_data, verify=True)

# Note: json_data will not be serialized by requests
# exactly as it was in the original request.
#data = '{ "password": "" }'
#response = requests.post('https://portainer.sectorq.eu/api/backup', headers=headers, data=data, verify=False)

with open(f'/share/docker_data/__backups/portainer_snapshot_{DATETIME}.tar.gz', 'wb') as f:
    f.write(response.content)