#!/usr/bin/env python3

"""
A tool to create a large partition at the end of MMCBLK
"""

import glob
import os
import re
import subprocess
import sys

MOUNT_DIR = '/data'
FS_TYPE = 'ext4'

device = subprocess.check_output(['findmnt', '-n', '-o', 'SOURCE', '/'], text=True)
match = re.search(r"/dev/mmcblk(?P<volume>\d)", device)
MMCBLK = '/dev/mmcblk' + match.group('volume')

pstring = subprocess.check_output(['parted', MMCBLK, 'unit', 's', 'print', 'free'], universal_newlines=True)
ptable_before = set(glob.glob(MMCBLK + '*'))
freesp = pstring.rstrip().split('\n')[-1]

if 'Free Space' not in freesp:
    raise IOError(f"No free space at the end of {MMCBLK}")

fspsplit = freesp.split()
subprocess.check_call(['parted', MMCBLK, 'mkpart',
                       'primary', fspsplit[0], fspsplit[1]])
subprocess.check_call(['partprobe', MMCBLK])

ptable_after = set(glob.glob(MMCBLK + '*'))
new_partition = (ptable_after - ptable_before).pop()

subprocess.check_call([f'mkfs.{FS_TYPE}', new_partition, '-F'])
with open('/etc/fstab', 'a') as f:
    f.write(f'\n{new_partition}  {MOUNT_DIR}   {FS_TYPE} defaults   0  0\n')
if not os.path.exists(MOUNT_DIR):
    os.mkdir(MOUNT_DIR)
subprocess.check_call(['mount', '-a'])
