#!/usr/bin/python
# start with sudo ./sdcard.py
# Copyright: 2015 Jens Carroll, Inventronik GmbH
# These sources are released under the terms of the MIT license: see LICENSE
"""
Description:
Sdcard - A utility to erase/copy/write an Atari(tm) hddriver to a sdcard.
Usage: sdcard.py drive
You must have root privileges to start sdcard.py
"""
import commands, sys, tty, termios, os

INPUT_FILE = './floppy_in.img'
OUTPUT_FILE = './floppy_out.img'

def parse_fdisk(fdisk_output):
  parts = []
  for line in fdisk_output.split("\n"):
    if line == '': continue
    parts = line.split()
    if parts[-1] == 'Sektoren':
      break
  if parts[-1] != 'Sektoren':
    print "fdisk -l is missing 'Sektoren' as identifier. Started with sudo?"
    exit(0)
  blocks = parts[-2]
  return blocks

def main():
  # Be sure we have root privileges
  if os.geteuid() != 0:
    exit("You need to have root privileges. Exiting.")

  if len(sys.argv) <= 1:
    exit("You have to provide a disk (e.g. /dev/sdb)")

  disk = sys.argv[1]
  fdisk_output = commands.getoutput("fdisk -l " + disk)
  blocks = parse_fdisk(fdisk_output)
  n = int(blocks) - 32768

  print "\nwf's SD-Card copy:"
  print "====================\n"
  print "ATTENTION: Make sure that " + disk + " is your SD-Card!!!"
  print "Found " + str(blocks) + " Blocks/Sektors on " + disk + "\n"
  print "c) Copy the SD card drives A and B to an image file"
  print "   (" + OUTPUT_FILE + ")"
  print "w) Write the image file to the SD card"
  print "   (" + INPUT_FILE + ")"
  print "e) Erase the floppy disk image from the SD card"
  print "q) Quit\n"

  fd = sys.stdin.fileno()
  old_settings = termios.tcgetattr(fd)
  tty.setraw(sys.stdin.fileno())

  sys.stdout.write('Choose: ')
  c = sys.stdin.read(1)
  print "\r"

  if c == "q":
    print "Quitting\n"
  elif c == "c":
    commands.getoutput("dd ibs=512 skip=" + str(n) + " count=32768 if=" + disk + " of=" + OUTPUT_FILE)
    print "Copying to harddrive (" + OUTPUT_FILE + ") - done\n"
  elif c == "w":
    commands.getoutput("dd obs=512 seek=" + str(n) + " count=32768 if=" + INPUT_FILE + " of=" + disk)
    print "Writing to SD-Card - done\n"
  elif c == "e":
    commands.getoutput("dd obs=512 seek=" + str(n) + " count=32768 if=/dev/zero of=" + disk)
    print "Erasing - done"
  else:
    print "Unkown option - quitting"

  print "\r"
  termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

if __name__ == "__main__":
  main()
