#!/usr/bin/python3

"""
Clone a Freeduc USB stick to the main hard disk: the target must be /dev/sda
"""

import glob, re, sys, time
from subprocess import Popen, call, PIPE
from ensure import ensure
from ownsense import ownDevice

def error(msg):
    print(msg)
    print("Aborting.")
    sys.exit(1)
    return

## check that we are running from a live Freeduc system
partition1, _ = ownDevice()

## get the source device, maybe /dev/sdb
sourceDevice=partition1[:-1]
if sourceDevice == "/dev/sda":
    error(f"Running {sys.argv[0]} from the hard disk is a nonsense.")

## guess the size of the ISO image
cmd = f"""sudo LANG=C /usr/sbin/sfdisk -l {sourceDevice} | grep '{sourceDevice}1'"""
reply, _ = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
m = re.match(r".* ([.\d]+)G.*", reply.decode())
size=float(m.group(1)) # size in GB

start = time.time()

# erase the boot data
call("dd if=/dev/zero of=/dev/sda bs=512 count=10", shell=True)

## remove swap space if any
call("swapoff --all", shell=True)

## compose the command to clone to the hard disk
cmd = f"/usr/bin/python3 /usr/lib/python3/dist-packages/live_clone/makeLiveStick.py --vfat-size 4 --no-persistence-seed --iso-filesize {size} --source own /dev/sda"
# launch the command makeLiveStick.py
call(cmd, shell=True)

## change the 3rd partition to swap type
cmd = "fdisk /dev/sda"
p = Popen(cmd, shell = True, stdin = PIPE, stdout = PIPE)
inputs = """\
t
3
82
w
"""
p.stdin.write(inputs.encode("utf-8"))
message,err=p.communicate()

## create the swap
call("mkswap /dev/sda3", shell = True)

## write a mention in /etc/fstab
call("mount /dev/sda4 /mnt", shell = True)
call("mkdir -p /mnt/rw/etc", shell = True)
call("mkdir -p /mnt/work", shell = True)
call("cp /etc/fstab /mnt/rw/etc/", shell = True)
call("echo '/dev/sda3 none swap sw 0 0' >>  /etc/fstab /mnt/rw/etc/fstab",
     shell = True)
call("umount /dev/sda4", shell = True)

duration = int(time.time() - start)
print(f"Cloning to hard disk finished, after {duration//60} minutes and {duration % 60:02d} seconds.")
