#!/bin/awk -f

BEGIN {
    # split input fields by a colon
    FS=":"
    IGNORECASE=1
    # set default language
    LANGUAGE="en_US.UTF8"
    # set translation domain
    TEXTDOMAIN = "alterator-amanda"
    BACKUP_VARIANTS_DIR = "/etc/amanda"
    AMCHECK = "/usr/sbin/amcheck"
    AMGETCONF = "/usr/sbin/amgetconf"
    AMDUMP = "/usr/sbin/amdump"
    AMFETCHDUMP = "/usr/sbin/amfetchdump"
    AMADMIN = "/usr/sbin/amadmin"
    READ_TEMPLATE = "cd /usr/share/alterator-amanda && "
    AMANDA_USER = "amanda"
    CHECK_RESULT = ""
    readmsg=0
    LOGFILE="/var/log/configd.log"
}

# error reporting function
function debug(text, errno) {
    printf "%s amanda: %s: %s\n", strftime("%B %d %H:%M:%S"), text, errno >> LOGFILE
    fflush(LOGFILE)
}

# remove leading and trailing spaces
function trim(arg) {
    gsub(/^[[:space:]]+/,"", arg)
    gsub(/[[:space:]]+$/,"", arg)
    return arg
}

# search a regular expression in a file
function grep(regex, file, line) {
    while ((error = getline line <file) > 0)
	if (line ~ regex) {
	    close(file)
	    return 1
	}
    if (error == -1)
	debug("Error reading file '" file "'", ERRNO)
    close(file)
    return 0
}

# quote name
function wrap(name) {
    return "(\"" name "\")"
}

# quote name/value pair
function wrap2(name, param, value) {
    return "(\"" name "\" " param " \"" value "\")"
}

# show translation
# overwriting locale settings
function N_(text, list, cmd, line) {
    split(LANGUAGE, list, /:/)
    cmd = "LANGUAGE=\"" LANGUAGE "\" LANG=\"" list[1] ".UTF8\" gettext " TEXTDOMAIN " \"" text "\""
    cmd | getline line
    close(cmd)
    return line
}

# print file contents skipping empty lines
function cat_file(file,	error, line) {
    while ((error = getline line <file) > 0) {
	if (line ~ /^[[:space:]]*$/)
	    continue
	print line
    }
    if (error == -1)
	debug("Error reading file '" file "'", ERRNO)
    close(file)
}

function find_backup_variants() {
    delete VARIANTS
    ind = 1
    cmd = "find " BACKUP_VARIANTS_DIR " -type f -name amanda.conf"
    while (cmd | getline variant) {
	count = split(variant, list, /\//)
	VARIANTS[ind] = list[count-1]
	++ind
    }
    if (close(cmd) != 0)
	debug("Cannot search backup variants in '" BACKUP_VARIANTS_DIR "'")
}

function check_backup_variant(variant) {
    cmd = "find " BACKUP_VARIANTS_DIR " -type f -name amanda.conf"
    while (cmd | getline variant) {
	count = split(variant, list, /\//)
	VARIANTS[ind] = list[count-1]
	++ind
    }
    if (close(cmd) != 0)
	debug("Cannot search backup variants in '" BACKUP_VARIANTS_DIR "'")
}

function list_backup_variants() {
    n = asort(VARIANTS)
    for (i = 1; i <= n; i++)
	print wrap(VARIANTS[i])
}

function list_params(param) {
    split(params["_objects"], list, /\//)
    if (list[1] == ".object")
	cmd = "su - -c \"" READ_TEMPLATE AMGETCONF " --list " param  "\" -s /bin/sh " AMANDA_USER
    else
	cmd = "su - -c \"" AMGETCONF " " list[1] " --list " param  "\" -s /bin/sh " AMANDA_USER
    while (cmd | getline message) {
	print wrap(message)
    }
    # Fixme: print error message from amgetconf
    close(cmd)
}

function get_global_param(variant,param) {
#    split(params["_objects"], list, /\//)
#    if (list[1] == ".object")
#	cmd = "su - -c \"" READ_TEMPLATE AMGETCONF " " param "\" -s /bin/sh " AMANDA_USER
#    else
        cmd = "su - -c \"" AMGETCONF " " variant " " param "\" -s /bin/sh " AMANDA_USER
    cmd | getline message
    close(cmd)
    return message
}

function quote(string) {
    if (string ~ /".*"/)
	return string
    else 
	return "\"" string "\""
}

function unquote(string) {
    quoted_reg = "\"([^\"]+)\""
    if (string ~ quoted_reg)
	return gensub(quoted_reg,"\\1","",string)
    else 
	return string
}

function write_all_params() {
    write_global_param("mailto",quote(params["mailto"]))
    write_global_param("tapetype",params["tapetype"])
    write_global_param("tpchanger",quote(params["tpchanger"]))
    write_global_param("tapedev",quote(params["tapedev"]))
}

function write_global_param(param, value) {
    param_inserted = 0
    param_reg = "(^[[:space:]]*" param ")(|[[:space:]]+[^#]*)(|#.*)$"
    commented_param_reg = "(^[[:space:]]*#+[[:space:]]*" param ")(|[[:space:]]+[^#]*)(|#.*)$"
    CONFIG_FILE = BACKUP_VARIANTS_DIR "/" params["_objects"] "/amanda.conf"
    if (grep(param_reg, CONFIG_FILE))
	param_exists = 1
    else
	param_exists = 0

    cmd = "mktemp"
    # FIXME: check mktemp exit status
    cmd | getline tempfile
    close(cmd)

    while ((error = getline line <CONFIG_FILE) > 0) {
	if (line ~ param_reg) {
    	    print gensub(param_reg,"\\1 " value " \\3","",line) >> tempfile
	} else if (line ~ commented_param_reg) {
    	    print line >> tempfile
    	    if (!param_exists && !param_inserted) {
        	print param " " value >> tempfile
        	param_inserted = 1
    	    }
	} else {
    	    print line >> tempfile
	}
    }
    if (!param_exists && !param_inserted) print param " " value >> tempfile
    if (error == -1)
	debug("Error reading file '" CONFIG_FILE "'", ERRNO)
    close(CONFIG_FILE)
    close(tempfile)
    system("cat " tempfile " > " CONFIG_FILE)
    system("rm -f " tempfile)
}

function disklist() {
    split(params["_objects"], list, /\//)
    DISKLIST_FILE = BACKUP_VARIANTS_DIR "/" list[1] "/disklist"
    disk_reg = "^[[:space:]]*([^# ]+)[[:space:]]+(\"[^\"]+\"|[^# ]+)[[:space:]]+([^# ]+)[[:space:]]*([[:space:]]+#.*)?$"

    while ((error = getline line <DISKLIST_FILE) > 0) {
	if (line ~ disk_reg) {
	    hostname = gensub(disk_reg,"\\1","",line)
	    diskname = unquote(gensub(disk_reg,"\\2","",line))
	    dumptype = gensub(disk_reg,"\\3","",line)
    	    print "(\"" hostname diskname "\" hostname \"" hostname "\" diskname \"" diskname "\" dumptype \"" dumptype "\")"
	}
    }
    if (error == -1)
	debug("Error reading file '" DISKLIST_FILE "'", ERRNO)
    close(DISKLIST_FILE)
}

function list_disk_for_backup() {
    split(params["_objects"], list, /\//)
    DISKLIST_FILE = BACKUP_VARIANTS_DIR "/" list[1] "/disklist"
    disk_reg = "^[[:space:]]*([^# ]+)[[:space:]]+(\"[^\"]+\"|[^# ]+)[[:space:]]+([^# ]+)[[:space:]]*([[:space:]]+#.*)?$"

    while ((error = getline line <DISKLIST_FILE) > 0) {
	if (line ~ disk_reg) {
	    hostname = gensub(disk_reg,"\\1","",line)
	    diskname = unquote(gensub(disk_reg,"\\2","",line))
	    dumptype = gensub(disk_reg,"\\3","",line)
    	    print "(\"" hostname diskname "\" hostname \"" hostname "\" diskname \"" diskname "\")"
	}
    }
    if (error == -1)
	debug("Error reading file '" DISKLIST_FILE "'", ERRNO)
    close(DISKLIST_FILE)
}

function strip_datetime(string) {
    gsub(/[- :]/,"",string)
    return string
}

function list_disk_for_restore() {
    split(params["_objects"], list, /\//)
    # FIXME: for now only localhost restoring supported
    # Long live for backend :)
    date_reg = "(19|20|21)[0-9][0-9]-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])"
    time_reg = "[0-2][0-9]:[0-5][0-9]:[0-5][0-9]"
    backups_reg = "^(" date_reg "[[:space:]]+(" time_reg "[[:space:]]+)?)([^ ]+)[[:space:]]+(\"[^\"]+\"|[^ ]+)[[:space:]]+.*"
    cmd = "su - -c \"" AMADMIN " " list[1] " find localhost\" -s /bin/sh " AMANDA_USER
    while (cmd | getline message) {
	if (message ~ backups_reg) {
	    datetime = gensub(backups_reg,"\\1","",message)
	    hostname = gensub(backups_reg,"\\6","",message)
	    diskname = unquote(gensub(backups_reg,"\\7","",message))
	    print "(\"" hostname strip_datetime(datetime) diskname "\" datetime \"" datetime "\" diskname \"" diskname "\")"
	}
    }
    close(cmd)
}

function duplicated_diskname(new_hostname, new_diskname) {
    split(params["_objects"], list, /\//)
    DISKLIST_FILE = BACKUP_VARIANTS_DIR "/" list[1] "/disklist"
    disk_reg = "^[[:space:]]*([^# ]+)[[:space:]]+(\"[^\"]+\"|[^# ]+)[[:space:]]+([^# ]+)[[:space:]]*([[:space:]]+#.*)?$"

    while ((error = getline line <DISKLIST_FILE) > 0) {
	if (line ~ disk_reg) {
	    hostname = gensub(disk_reg,"\\1","",line)
	    diskname = unquote(gensub(disk_reg,"\\2","",line))
	    gsub(/\//,"_",diskname)
	    gsub(/\//,"_",new_diskname)
	    if (hostname == new_hostname && diskname == new_diskname) {
		close(DISKLIST_FILE)
		return 1
	    }
	}
    }
    if (error == -1)
	debug("Error reading file '" DISKLIST_FILE "'", ERRNO)
    close(DISKLIST_FILE)
    return 0
}

function add_to_disklist(hostname, diskname, dumptype) {
    split(params["_objects"], list, /\//)
    DISKLIST_FILE = BACKUP_VARIANTS_DIR "/" list[1] "/disklist"
    if (duplicated_diskname(hostname, diskname))
	print "(error \"Pair \\\"" hostname " " diskname "\\\" already exists.\")"
    else {
	system("echo '" hostname " " quote(diskname) " " dumptype "' >> " DISKLIST_FILE)
	print "()"
    }
}

function delete_from_disklist(hostname, diskname, dumptype) {
    split(params["_objects"], list, /\//)
    DISKLIST_FILE = BACKUP_VARIANTS_DIR "/" list[1] "/disklist"
    disk_reg = "^[[:space:]]*" hostname "[[:space:]]+(" diskname "|\"" diskname "\")[[:space:]]+" dumptype ".*"

    cmd = "mktemp"
    # FIXME: check mktemp exit status
    cmd | getline tempfile
    close(cmd)

    while ((error = getline line <DISKLIST_FILE) > 0) {
	if (line ~ disk_reg) {
	} else {
    	    print line >> tempfile
	}
    }
    if (error == -1)
	debug("Error reading file '" DISKLIST_FILE "'", ERRNO)
    close(DISKLIST_FILE)
    close(tempfile)
    system("cat " tempfile " > " DISKLIST_FILE)
    system("rm -f " tempfile)
}

function do_backup(hostname, diskname) {
    split(params["_objects"], list, /\//)
    cmd = "su - -c \"" AMDUMP " " list[1] " " hostname  " '" diskname "'\" -s /bin/sh " AMANDA_USER
    system(cmd)
}

function do_restore(diskname, datetime) {
    split(params["_objects"], list, /\//)
    cmd = "mkdir -p '" diskname "' && cd '" diskname "' && " AMFETCHDUMP " -a -p " list[1] " localhost '" diskname "' " strip_datetime(datetime) " | /bin/tar -xpGf -" 
    system(cmd)
}

# start message reading
/^_message:begin$/ {
    readmsg=1
    next
}

# stop message reading
/^_message:end$/ {
    readmsg=0
    debug("==========", "==========")
    for (attribute in params)
	debug("params[" attribute "]", params[attribute])
    # overwrite current language
    if (params["language"] != "")
	LANGUAGE = gensub(/;/, ":", "g", params["language"])

    switch (params["action"]) {
	case "constraints":
	    switch (params["_objects"]) {
		case "/":
		    printf "(name (required #t match (\"^[a-zA-Z]+[^[:space:]]*$\" \"%s\") label \"%s\" ))", \
		    N_("should starts with latin letter"), N_("Configuration name")
		    break
		default:
		    print "()"
	    }
	    break
	case "backup":
	    if (params["backup"] == "#t") {
		do_backup(params["hostname"], params["diskname"])
	    }
	    print "()"
	    break
	case "restore":
	    if (params["restore"] == "#t") {
		do_restore(params["diskname"],params["datetime"])
	    }
	    print "()"
	    break
	case "delete":
	    # Check for actual deletion. Sometimes action 'delete' invoked without "delete = #t"
	    if (params["delete"] == "#t") {
		# Get type of deletion from _objects
		split(params["_objects"], list, /\//)
		switch (list[2]) {
		case "disklist":
		    delete_from_disklist(params["hostname"], params["diskname"], params["dumptype"])
		    print "()"
		    break
		default:
		    cmd = "/usr/share/alterator-amanda/delete-configuration.sh " params["_objects"] " \"delete backup\"" " &> /dev/null"
		    # FIXME: check cmd result
		    system(cmd)
		    print "()"
		}
	    }
	    else {
		print "()"
	    }
	    break
	case "new":
	    switch (params["type"]) {
	    case "disklist":
		add_to_disklist(params["hostname"], params["diskname"], params["dumptype"])
		break
	    default:
		found = 0
		for (i in VARIANTS)
		    if (VARIANTS[i] == params["name"]) {
			found = 1
		    }
		if (found == 0) {
		    if (params["name"] == "gnutar-lists" || params["name"] == "vtapes")
			printf "(error \"Name \\\"%s\\\" used by Amanda internals\")", params["name"]
		    else {
			cmd = "/usr/share/alterator-amanda/prepare-configuration.sh /usr/share/alterator-amanda/ " params["name"] " &> /dev/null"
			# FIXME: check cmd result
			system(cmd)
			print "()"
		    }
		}
		else {
		    print "(error \"Configuration name already exists\")"
		}
	    }
	    break
	case "list": 
	    print "("
	    switch (params["_objects"]) {
		case /tapetype_list\y/: 
    		    list_params("tapetype")
		    break
		case /dumptype_list\y/: 
    		    list_params("dumptype")
		    break
		case /holdingdisk_list\y/: 
    		    list_params("holdingdisk")
		    break
		case /tpchanger_list\y/: 
		    print wrap("chg-disk")
		    print wrap("chg-multi")
		    print wrap("chg-manual")
		    print wrap("chg-mtx")
		    print wrap("chg-zd-mtx")
		    print wrap("chg-scsi-chio")
		    print wrap("chg-scsi")
		    print wrap("chg-chio")
		    print wrap("chg-chs")
		    print wrap("chg-rth")
		    print wrap("chg-juke")
		    print wrap("chg-rait")
		    print wrap("chg-iomega")
		    print wrap("chg-null")
		    break
		case /disklist\y/: 
		    disklist()
		    break
		case /list_disk_for_backup\y/: 
		    list_disk_for_backup()
		    break
		case /list_disk_for_restore\y/: 
		    list_disk_for_restore()
		    break
		default:
		    find_backup_variants()
		    list_backup_variants()

	    }
	    print ")"
	    break
	case "read": 
	    print "("
	    switch (params["_objects"]) {
		case "/":
		    find_backup_variants()
		    break
		default:
		    printf " tapetype \"%s\"", get_global_param(params["_objects"],"tapetype")
		    printf " mailto \"%s\"", get_global_param(params["_objects"],"mailto")
		    printf " tpchanger \"%s\"", get_global_param(params["_objects"],"tpchanger")
		    printf " tapedev \"%s\"", get_global_param(params["_objects"],"tapedev")
		    printf " variant \"%s\"", params["_objects"]
		    print  " dumptype \"compressed-tar\""
		    print  " hostname \"localhost\""
	    }
	    print ")"
	    break	    
# Check	for configuration is correct
# cmd = "su - -c \"" AMCHECK " -s " params["variant"] " 2> /dev/null \" -s /bin/sh " AMANDA_USER
	case "write":
	    write_all_params()
	    print "()"
	    break
	default:
	    print "#f"
    }
    fflush()
    # delete attribute/value pairs before next cycle
    delete params
    #exit
    next
}

# save attribute/value pairs
{
    if (! readmsg)
	next
    attribute=$1
    value=$2
    # join the rest of fields with a colon
    for (n = 3; n <= NF; n++)
	value=value ":" $n
    value = gensub(/([^\\])\\n/, "\\1\n", "g", value)
    params[attribute]=value
}
